Replace Numbers of Continuous ggplot2 Legend by Text in R (Example Code)

In this R tutorial you’ll learn how to replace the values of a continuous ggplot2 legend by text.

Preparing the Example

set.seed(289367)                                   # Example data
my_df <- data.frame(expand.grid(x = 0:5, y = 0:5),
                   z = rnorm(36))
head(my_df)
#   x y           z
# 1 0 0 -1.75255286
# 2 1 0 -0.22511947
# 3 2 0  1.00520336
# 4 3 0  1.23412700
# 5 4 0 -0.05995937
# 6 5 0 -1.11686047
install.packages("ggplot2")                        # Install ggplot2 package
library("ggplot2")                                 # Load ggplot2
my_plot <- ggplot(my_df, aes(x, y, fill = z)) +    # ggplot2 plot with default legend
  geom_tile()
my_plot

r graph figure 1 replace numbers continuous ggplot2 legend text r

Example: Label Minimum & Maximum of ggplot2 Legend Using scale_fill_gradientn() Function

my_plot +                                          # Change numbers in ggplot2 legend
  scale_fill_gradientn(colors = 1:10,
                       breaks = c(min(my_df$z), mean(my_df$z), max(my_df$z)),
                       labels = c("Lowest", "Middle", "Highest"))

r graph figure 2 replace numbers continuous ggplot2 legend text r

Further Resources

You may find some related R tutorials on topics such as ggplot2, plot legends, and labels in the following list:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top