In order to focus on the construction of the different plots and the use of {ggplot2}, we will restrict ourselves to drawing basic (yet beautiful) plots without unnecessary layers. For the sake of completeness, we will briefly discuss and illustrate different layers to further personalize a plot at the end of the article (see this section).

Note that if you still struggle to create plots with {ggplot2} after reading this tutorial, you may find the {esquisse} addin useful. This addin allows you to interactively (that is, by dragging and dropping variables) create plots with the {ggplot2} package. Give it a try!

Scatter plot

We start by creating a scatter plot using geom_point. Remember that a scatter plot is used to visualize the relation between two quantitative variables.

  1. We start by specifying the data:
1
ggplot(dat) # data

  1. Then we add the variables to be represented with the aes() function:
1
2
ggplot(dat) + # data
aes(x = displ, y = hwy) # variables

  1. Finally, we indicate the type of plot:
1
2
3
ggplot(dat) + # data
aes(x = displ, y = hwy) + # variables
geom_point() # type of plot

You will also sometimes see the aesthetic elements (aes() with the variables) inside the ggplot() function in addition to the dataset:

1
2
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point()

This second method gives the exact same plot than the first method. I tend to prefer the first method over the second for better readability, but this is more a matter of taste so the choice is up to you.

Line plot

Line plots, particularly useful in time series or finance, can be created similarly but by using geom_line():

1
2
3
ggplot(dat) +
aes(x = displ, y = hwy) +
geom_line()

(Note that this might not be the most appropriate plot since there are multiple points for each value of displ, but this is just an example to show how to create a line plot.)

Combination of line and points

An advantage of {ggplot2} is the ability to combine several types of plots and its flexibility in designing it. For instance, we can add a line to a scatter plot by simply adding a layer to the initial scatter plot:

1
2
3
4
ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point() +
geom_line() # add line

Histogram

A histogram (useful to visualize distributions and detect potential outliers) can be plotted using geom_histogram():

1
2
3
ggplot(dat) +
aes(x = hwy) +
geom_histogram()

By default, the number of bins is equal to 30. You can change this value using the bins argument inside the geom_histogram() function:

1
2
3
ggplot(dat) +
aes(x = hwy) +
geom_histogram(bins = round(sqrt(nrow(dat))))

Here I specify the number of bins to be equal to the square root of the number of observations (following Sturge’s rule) but you can specify any integer number.

Density plot

Density plots can be created using geom_density():

1
2
3
ggplot(dat) +
aes(x = hwy) +
geom_density()

Combination of histogram and densities

We can also superimpose a histogram and a density curve on the same plot:

1
2
3
4
ggplot(dat) +
aes(x = hwy, y = after_stat(density)) +
geom_histogram() +
geom_density()

Or superimpose several densities:

1
2
3
ggplot(dat) +
aes(x = hwy, color = drv, fill = drv) +
geom_density(alpha = 0.25) # add transparency

The argument alpha = 0.25 has been added for some transparency. More information about this argument can be found in this section.

Dotplot

A dotplot in {ggplot2} can be built with geom_dotplot():

1
2
3
4
# Dotplot for one variable
ggplot(dat) +
aes(x = "", y = hwy) +
geom_dotplot(binaxis = "y", stackdir = "center")

1
2
3
4
5
6
7
# Dotplot by factor
ggplot(dat) +
aes(x = drv, y = hwy) +
geom_dotplot(
binaxis = "y", stackdir = "center",
dotsize = 0.75 # decrease dot size
)

Dotplots are more appropriate with small samples (because the plot may be hard to read with too many points). For large samples, a boxplot may be used.

For the interested reader, see many personalization that is possible with a dotplot in this tutorial.

Boxplot

A boxplot (also very useful to visualize distributions and detect potential outliers) can be plotted using geom_boxplot():

1
2
3
4
# Boxplot for one variable
ggplot(dat) +
aes(x = "", y = hwy) +
geom_boxplot()

1
2
3
4
# Boxplot by factor
ggplot(dat) +
aes(x = drv, y = hwy) +
geom_boxplot()

It is also possible to plot the points on the boxplot with geom_jitter(), and to vary the width of the boxes according to the size (i.e., the number of observations) of each level with varwidth = TRUE:

1
2
3
4
ggplot(dat) +
aes(x = drv, y = hwy) +
geom_boxplot(varwidth = TRUE) + # vary boxes width according to n obs.
geom_jitter(alpha = 0.25, width = 0.2) # adds random noise and limit its width

The geom_jitter() layer adds some random variation to each point in order to prevent them from overlapping (an issue known as overplotting).1 Moreover, the alpha argument adds some transparency to the points (see more in this section) to keep the focus on the boxes and not on the points.

Finally, it is also possible to divide boxplots into several panels according to the levels of a qualitative variable:

1
2
3
4
5
ggplot(dat) +
aes(x = drv, y = hwy) +
geom_boxplot(varwidth = TRUE) + # vary boxes width according to n obs.
geom_jitter(alpha = 0.25, width = 0.2) + # adds random noise and limit its width
facet_wrap(~year) # divide into 2 panels

For a visually more appealing plot, it is also possible to use some colors for the boxes depending on the x variable:

1
2
3
4
5
6
ggplot(dat) +
aes(x = drv, y = hwy, fill = drv) + # add color to boxes with fill
geom_boxplot(varwidth = TRUE) + # vary boxes width according to n obs.
geom_jitter(alpha = 0.25, width = 0.2) + # adds random noise and limit its width
facet_wrap(~year) + # divide into 2 panels
theme(legend.position = "none") # remove legend

In that case, it best to remove the legend as it becomes redundant. See more information about the legend in this section.

If you are unhappy with the default colors provided in {ggplot2}, you can change them manually with the scale_fill_manual() layer:

1
2
3
4
5
6
7
ggplot(dat) +
aes(x = drv, y = hwy, fill = drv) + # add color to boxes with fill
geom_boxplot(varwidth = TRUE) + # vary boxes width according to n obs.
geom_jitter(alpha = 0.25, width = 0.2) + # adds random noise and limit its width
facet_wrap(~year) + # divide into 2 panels
theme(legend.position = "none") + # remove legend
scale_fill_manual(values = c("darkred", "darkgreen", "steelblue")) # change fill color manually

Barplot

A barplot (useful to visualize qualitative variables) can be plotted using geom_bar():

1
2
3
ggplot(dat) +
aes(x = drv) +
geom_bar()

Bars’ heights correspond to the observed frequencies (i.e., the number of observations) for each level of the variable of interest (drv in our case).

Tip: by default, the order of the bars follows the initial order (by alphabetical order or numerical order if you did not change it). If you want to order the levels by frequency (largest first), use the fct_infreq() function from the {forcats} package.

1
2
3
4
5
library(forcats)

ggplot(dat) +
aes(x = fct_infreq(drv)) + # order by frequency
geom_bar()

If you want to order levels in an increasing order (i.e., category with the smallest frequency first), use the fct_rev() in addition to the fct_infreq() function:

1
2
3
ggplot(dat) +
aes(x = fct_rev(fct_infreq(drv))) + # order by frequency
geom_bar()

(Label for the x-axis can then easily be edited with the labs() function. See below for more information.)

Again, for a more appealing plot, we can add some colors to the bars with the fill argument:

1
2
3
4
ggplot(dat) +
aes(x = drv, fill = drv) + # add colors to bars
geom_bar() +
theme(legend.position = "none") # remove legend

We can also create a barplot with two qualitative variables:

1
2
3
ggplot(dat) +
aes(x = drv, fill = year) + # fill by years
geom_bar()

In order to compare proportions across groups, it is best to make each bar the same height using position = "fill":

1
2
ggplot(dat) +
geom_bar(aes(x = drv, fill = year), position = "fill")

To draw the bars next to each other for each group, use position = "dodge":

1
2
ggplot(dat) +
geom_bar(aes(x = drv, fill = year), position = "dodge")

Raincloud plot

A raincloud plot is a graph that combines 3 visualizations:

  1. a density plot,
  2. a boxplot,
  3. and the raw data in the form of a dotplot or jittered points.

The advantage of this plot is that it illustrates, all at once, the distribution (with the density curve), the summary measures (first, second and third quartiles, and maximum/mininum without outliers thanks to the boxplot) and the number of observations (either via a dotplot or via jittered points).

Let’s illustrate the raincloud plot, first with jittered points (more appropriate with large samples):2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
library(tidyverse)
library(ggdist)

# density plot:
dat %>%
ggplot(aes(x = drv, y = hwy, fill = drv)) +
stat_halfeye(
adjust = 0.5, # set the smoothing parameter
width = 0.5, # set the height of the curves
justification = -0.2, # move curves to the right
.width = 0, point_colour = NA # remove interval present by default
) +
# boxplot:
geom_boxplot(
width = 0.12, # width of boxes
outlier.color = NA, # remove color of outliers
alpha = 0.5 # add transparency
) +
# jittered points:
geom_point(aes(colour = drv), # add color on points
size = 1.3, # size of points
alpha = .3, # add transparency
position = position_jitter( # obtain shifted points
seed = 1, # set seed for same random representation
width = .09 # manage the width of the offset
)
) +
# further personalization:
coord_flip() + # rotate plot
theme(legend.position = "none") # remove legend

Now the same chart but with dotplots this time (more appropriate with small samples):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# density plot:
dat %>%
sample_n(100) %>% # random sample of size 100
ggplot(aes(x = drv, y = hwy, fill = drv)) +
stat_halfeye(
adjust = 0.5, # set the smoothing parameter
width = 0.5, # set the height of the curves
justification = -0.2, # move curves to the right
.width = 0, point_colour = NA # remove interval present by default
) +
# boxplot:
geom_boxplot(
width = 0.12, # width of boxes
outlier.color = NA, # remove color of outliers
alpha = 0.5 # add transparency
) +
# dotplot:
stat_dots(
dotsize = 0.5, # size of points
side = "left", # place points on opposite side of density curve
justification = 1.1, # move points away from boxplot
binwidth = 1 # group points together
) +
# further personalization:
coord_flip() + # rotate plot
theme(legend.position = "none") # remove legend

The code is much longer compared to the other plots, but the only line(s) to edit to adapt to your dataset is the aesthetics (aes()). The rest is mainly adjustments that should not be changed.

You may have notice that at the end of the code, there are some personalization which allow to improve the plot even further. The most common personalization are presented in the next section.

Further personalization

Title and axis labels

The first things to personalize in a plot is the labels to make the plot more informative to the audience. We can easily add a title, subtitle, caption and edit axis labels with the labs() function:

1
2
3
4
5
6
7
8
9
10
11
p <- ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point()

p + labs(
title = "Fuel efficiency for 38 popular models of car",
subtitle = "Period 1999-2008",
caption = "Data: ggplot2::mpg. See more at statsandr.com",
x = "Engine displacement (litres)",
y = "Highway miles per gallon (mpg)"
)

As you can see in the above code, you can save one or more layers of the plot in an object for later use.

This way, you can save your “main” plot, and add more layers of personalization until you get the desired output. Here we saved the main scatter plot in an object called p and we will refer to it for the subsequent personalization.

You can also edit the alignment, the size and the shape of the title and subtitle via the theme() layer and the element_text() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
p + labs(
title = "Fuel efficiency for 38 popular models of car",
subtitle = "Period 1999-2008",
caption = "Data: ggplot2::mpg. See more at statsandr.com",
x = "Engine displacement (litres)",
y = "Highway miles per gallon (mpg)"
) +
theme(
plot.title = element_text(
hjust = 0.5, # center
size = 12,
color = "steelblue",
face = "bold"
),
plot.subtitle = element_text(
hjust = 0.5, # center
size = 10,
color = "gray",
face = "italic"
)
)

If the title or subtitle is long and you want to divide it into multiple lines, use \n:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
p + labs(
title = "Fuel efficiency for 38 popular \n models of car",
subtitle = "Period 1999-2008",
caption = "Data: ggplot2::mpg. See more at statsandr.com",
x = "Engine displacement (litres)",
y = "Highway miles per gallon (mpg)"
) +
theme(
plot.title = element_text(
hjust = 0.5, # center
size = 12,
color = "steelblue",
face = "bold"
),
plot.subtitle = element_text(
hjust = 0.5, # center
size = 10,
color = "gray",
face = "italic"
)
)

Axis ticks

Axis ticks can be adjusted using scale_x_continuous() and scale_y_continuous() for the x and y-axis, respectively:

1
2
3
# Adjust ticks
p + scale_x_continuous(breaks = seq(from = 1, to = 7, by = 0.5)) + # x-axis
scale_y_continuous(breaks = seq(from = 10, to = 45, by = 5)) # y-axis

Log transformations

In some cases, it is useful to plot the log transformation of the variables. This can be done with the scale_x_log10() and scale_y_log10() functions:

1
2
p + scale_x_log10() +
scale_y_log10()

Limits

The most convenient way to control the limits of the plot is to use again the scale_x_continuous() and scale_y_continuous() functions in addition to the limits argument:

1
2
p + scale_x_continuous(limits = c(3, 6)) +
scale_y_continuous(limits = c(20, 30))

It is also possible to simply take a subset of the dataset with the subset() or filter() function. See how to subset a dataset if you need a reminder.

Scales for better axis formats

Depending on your data, it is possible to format axes in a certain way with the {scales} package. The format I use the most is comma which formats large numbers in a more-readable way.

For this example, we multiply both variables by 10000 to have larger numbers and then we apply the format to the y-axis (only to the y-axis so we can see the difference with the x-axis which is not formatted):

1
2
3
4
ggplot(dat) +
aes(x = displ * 10000, y = hwy * 10000) +
geom_point() +
scale_y_continuous(labels = scales::comma) # format y-axis

As you can see, numbers on the y-axis are displayed as 200,000, 300,000, etc. instead of 200000, 300000, etc., which makes it more readable.

Another common format is percent to display numbers as percentages:

1
2
3
4
ggplot(dat) +
aes(x = displ, y = hwy / 100) +
geom_point() +
scale_y_continuous(labels = scales::percent) # format y-axis

These two formats make large numbers and percentages easier to read. Other formats are possible such as using dollar signs, dates etc. See more information in the package’s documentation.

Legend

By default, the legend is located to the right side of the plot (when there is a legend to be displayed of course).

To control the position of the legend, we need to use the theme() function in addition to the legend.position argument:

1
2
p + aes(color = class) +
theme(legend.position = "top")

Replace "top" by "left" or "bottom" to change its position and by "none" to remove it.

The title of the legend can be edited with the labs() layer:

1
2
p + aes(color = class) +
labs(color = "Car's class")

Note that the argument inside labs() must match the one inside the aes() layer (in this case: color).

The title of the legend can also be removed with legend.title = element_blank() inside the theme() layer:

1
2
3
4
5
p + aes(color = class) +
theme(
legend.title = element_blank(),
legend.position = "bottom"
)

The legend now appears at the bottom of the plot, without the legend title.

Shape, color, size and transparency

There are a very large number of options to improve the quality of the plot or to add additional information. These include:

  • shape,
  • size,
  • color, and
  • alpha (transparency).

We can for instance change the shape of all points in a scatter plot by adding shape to geom_point(), or vary the shape according to the values taken by another variable (in that case, the shape argument must be inside aes()):3

1
2
3
4
# Change shape of all points
ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point(shape = 4)

1
2
3
4
# Change shape of points based on a categorical variable
ggplot(dat) +
aes(x = displ, y = hwy, shape = drv) +
geom_point()

Following the same principle, we can modify the color, size and transparency of the points based on a qualitative or quantitative variable. Here are some examples:

1
2
3
4
5
6
p <- ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point()

# Change color for all points
p + geom_point(color = "steelblue")

1
2
# Change color based on a qualitative variable
p + aes(color = drv)

1
2
# Change color based on a quantitative variable
p + aes(color = cty)

1
2
# Change color based on a criterion (median of cty variable)
p + aes(color = cty > median(cty))

1
2
# Change size of all points
p + geom_point(size = 4)

1
2
# Change size of points based on a quantitative variable
p + aes(size = cty)

1
2
# Change transparency based on a quantitative variable
p + aes(alpha = cty)

We can of course mix several options (shape, color, size, alpha) to build more complex graphics:

1
2
p + geom_point(size = 0.5) +
aes(color = drv, shape = year, alpha = cty)

If you are unhappy with the default colors, you can change them manually with the scale_colour_manual() layer (for qualitative variables) and the scale_coulour_gradient2() layer (for quantitative variables):

1
2
3
# Change color based on a qualitative variable
p + aes(color = drv) +
scale_colour_manual(values = c("red", "blue", "green"))

1
2
3
4
5
6
7
8
# Change color based on a quantitative variable
p + aes(color = cty) +
scale_colour_gradient2(
low = "green",
mid = "gray",
high = "red",
midpoint = median(dat$cty)
)

For your information, you can emulate {ggplot2} default color palette for a desired number of colors and produce a character vector of HEX colors. For example, with 4 colors:

1
2
library(scales)
show_col(hue_pal()(4))

Text and labels

To add a label on a point (for example the row number), we can use the geom_text() and aes() functions:

1
2
3
4
5
p + geom_text(aes(label = rownames(dat)),
check_overlap = TRUE,
size = 2,
vjust = -1
)

To add text on the plot, we use the annotate() function:

1
2
3
4
5
6
p + annotate("text",
x = 6,
y = 40,
label = "hwy and displ are \n negatively correlated \n (rho = -0.77, p-value < 0.001)",
size = 3
)

Read the article on correlation coefficient and correlation test in R to see how I computed the correlation coefficient (rho) and the _p_-value of the correlation test.

Smooth and regression lines

In a scatter plot, it is possible to add a smooth line fitted to the data:

1
p + geom_smooth()

In the context of simple linear regression, it is often the case that the regression line is displayed on the plot.

This can be done by adding method = lm (lm stands for linear model) in the geom_smooth() layer:

1
p + geom_smooth(method = lm)

It is also possible to draw a regression line for each level of a categorical variable:

1
2
p + aes(color = drv, shape = drv) +
geom_smooth(method = lm, se = FALSE)

The se = FALSE argument removes the confidence interval around the regression lines.

Facets

facet_grid allows you to divide the same graphic into several panels according to the values of one or two qualitative variables:

1
2
# According to one variable
p + facet_grid(. ~ drv)

1
2
# According to 2 variables
p + facet_grid(drv ~ year)

It is then possible to add a regression line to each facet:

1
2
p + facet_grid(. ~ drv) +
geom_smooth(method = lm)

facet_wrap() can also be used, as illustrated in this section.

Themes

Several functions are available in the {ggplot2} package to change the theme of the plot.

The most common themes after the default theme (i.e., theme_gray()) are the black and white (theme_bw()), minimal (theme_minimal()) and classic (theme_classic()) themes:

1
2
# Black and white theme
p + theme_bw()

1
2
# Minimal theme
p + theme_minimal()

1
2
# Classic theme
p + theme_classic()

I tend to use the minimal theme for most of my R Markdown reports as it brings out the patterns and points and not the layout of the plot, but again this is a matter of personal taste. See more themes at ggplot2.tidyverse.org/reference/ggtheme.html and in the {ggthemes} package.

In order to avoid having to change the theme for each plot you create, you can change the theme for the current R session using the theme_set() function as follows:

1
theme_set(theme_minimal())

Interactive plot with {plotly}

You can easily make your plots created with {ggplot2} interactive with the {plotly} package:

1
2
library(plotly)
ggplotly(p + aes(color = year))

You can now hover over a point to display more information about that point. There is also the possibility to zoom in and out, to download the plot, to select some observations, etc. More information about {plotly} for R can be found here.

Combine plots with {patchwork}

There are several ways to combine plots made in {ggplot2}. In my opinion, the most convenient way is with the {patchwork} package using symbols such as +, / and parentheses.

We first need to create some plots and save them:

1
2
3
4
5
6
7
8
9
10
11
p_a <- ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point()

p_b <- ggplot(dat) +
aes(x = hwy) +
geom_histogram()

p_c <- ggplot(dat) +
aes(x = drv, y = hwy) +
geom_boxplot()

Now that we have 3 plots saved in our environment, we can combine them. To have plots next to each other simply use the + symbol:

1
2
library(patchwork)
p_a + p_b + p_c

To display them above each other simply use the / symbol:

1
p_a / p_b / p_c

And finally, to combine them above and next to each other, mix +, / and parentheses:

1
p_a + p_b / p_c

1
(p_a + p_b) / p_c

See more ways to combine plots with:

  • grid.arrange() from the {gridExtra} package
  • plot_grid() from the {cowplot} package

Flip coordinates

Flipping coordinates of your plot is useful to create horizontal boxplots, or when labels of a variable are so long that they overlap each other on the x-axis. See with and without flipping coordinates below:

1
2
3
4
5
6
7
8
9
10
11
12
13
# without flipping coordinates
p1 <- ggplot(dat) +
aes(x = class, y = hwy) +
geom_boxplot()

# with flipping coordinates
p2 <- ggplot(dat) +
aes(x = class, y = hwy) +
geom_boxplot() +
coord_flip()

library(patchwork)
p1 + p2 # left: without flipping, right: with flipping

This can be done with many types of plot, not only with boxplots. For instance, if a categorical variable has many levels or the labels are long, it is usually best to flip the coordinates for a better visual:

1
2
3
4
ggplot(dat) +
aes(x = class) +
geom_bar() +
coord_flip()

Save plot

The ggsave() function will save the most recent plot in your current working directory unless you specify a path to another folder:

1
2
3
4
5
ggplot(dat) +
aes(x = displ, y = hwy) +
geom_point()

ggsave("plot1.pdf")

You can also specify the width, height and resolution (dpi) as follows:

1
2
3
4
5
6
ggsave("plot1.pdf",
width = 12,
height = 12,
units = "cm",
dpi = 300
)

Managing dates

If the time variable in your dataset is in date format, the {ggplot2} package recognizes the date format and automatically uses a specific type for the axis ticks.

There is no time variable with a date format in our dataset, so let’s create a new variable of this type thanks to the as.Date() function:

1
2
dat$date <- as.Date("2020-08-21") - 0:(nrow(dat) - 1)

See the first 6 observations of this date variable and its class

1
head(dat$date)
1
2
## [1] "2020-08-21" "2020-08-20" "2020-08-19" "2020-08-18" "2020-08-17"
## [6] "2020-08-16"
1
str(dat$date)
1
##  Date[1:234], format: "2020-08-21" "2020-08-20" "2020-08-19" "2020-08-18" "2020-08-17" ...

The new variable date is correctly specified in a date format.

Most of the time, with a time variable, we want to create a line plot with the date on the X-axis and another continuous variable on the Y-axis, like the following plot for example:

1
2
3
4
p <- ggplot(dat) +
aes(x = date, y = hwy) +
geom_line()
p

As soon as the time variable is recognized as a date, we can use the scale_x_date() layer to change the format displayed on the X-axis. The following table shows the most frequent date formats:

Source: www.statmethods.net

Source: www.statmethods.net

Run ?strptime() to see many more date formats available in R.

For this example, let’s add the year in addition to the unabbreviated month:

1
p + scale_x_date(date_labels = "%B %Y")

It also possible to control the breaks to display on the X-axis with the date_breaks argument. For this example, let’s say we want to display the day as number and the abbreviated month for each interval of 10 days:

1
p + scale_x_date(date_breaks = "10 days", date_labels = "%d %b")

If labels displayed on the X-axis are unreadable because they overlap each other, you can rotate them with the theme() layer and the angle argument:

1
2
p + scale_x_date(date_breaks = "10 days", date_labels = "%d %b") +
theme(axis.text.x = element_text(angle = 60, hjust = 1))

Highlight data with {gghighlight}

The {gghighlight} package allows, as its name suggests, to highlight some data directly on your ggplot. The highlighted data (that you define) are shown in bright color and the rest in gray.

Below example of how it works for a scatter plot, boxplot, barplot and histogram.

1
2
3
4
5
6
7
library(gghighlight)

# scatter plot
ggplot(mpg, aes(x = displ, y = hwy, color = cyl)) +
geom_point() +
gghighlight(cyl == "8") +
theme(legend.position = "none") # remove legend

1
2
3
4
5
6
# boxplot
ggplot(dat) +
aes(x = drv, y = hwy, fill = drv) +
geom_boxplot() +
gghighlight(drv %in% c("r", "4")) +
theme(legend.position = "none") # remove legend

1
2
3
4
5
# barplot
ggplot(dat) +
aes(x = drv, fill = drv) +
geom_bar() +
gghighlight(drv == "f")

As you can see, the gghighlight() layer accepts different types of conditions, but also several of them at the same time:

1
2
3
4
5
# histogram
ggplot(dat) +
aes(x = hwy, fill = year) +
geom_histogram() +
gghighlight(displ &gt; 2 &amp; year == "1999")