Ggplot R plot not showing up in RStudio

When working with RStudio you define a plot (either with R-base or ggplot2), but the chart doesn’t show up in the Plots tab in RStudio. Most probably, you can solve this issue by explicitly printing your plot:


Display R plot if not showing up in RStudio

Follow the steps below to print your R-base or ggplot chart in RStudio:

Step 1: Create your Data

First off, we will create a simple R DataFrame, which we will use for our plotting. You could generate this data manually, or import from an external file, database or API.

# Initialize R DataFrame
office <- c ('North', 'North East', 'East', 'South', 'South West', 'West')
sales <- c (97.0, 186.0, 136.0, 160.0, 234.0, 160.0)
quarter <- c (1, 2, 1, 2, 1,2)
sales_df <- data.frame (office = office, quarter = quarter, sales = sales)

Step 2: Define your plot canvas, data and geometry

Next we will import the ggplot2 library and build the chart. First we’ll define a canvas, then define the data set we will use (we previously created it in step 1), then define the chart aesthetics and type. Last, we define a title for chart and axes.

  sales_plot <- ggplot(sales_df, aes (x = office, y = sales)) +
               geom_col() +
               labs(title="Sales by Office", x = "Sales Office", y="Sales Amount")+

Important Note: Make sure to import the ggplot2 library package before using it in your R script.

Step 3: Show your plot

This is the key part – you have to make sure to explicitly print your chart.

print (sales_plot)

Here’s our bar / columns chart as shown in RStudio Plots tab:


How to add a legend to my ggplot chart?

Use the legend-position setting to add a legend to your ggplot. Add the following code to the snippet we have provided above:

# your ggplot code here
theme_minimal() + theme(legend.position = "bottom")

How to increase or decrease my ggplot area?

You can use the following code when rendering your plot:

theme ( plot.width = 7, plot.height = 5 )

You can also use the ggsave function:

ggsave("sales_plot.png", sales_plot, height = 5, width = 7)