watchtower watchtower - 3 months ago 15
R Question

Breaks in ggplot2

I've been reading Wickham's guide. I understand that scale_identity function uses the value contained in the variable to do the scaling. However, I am not quite sure what "breaks = df$colour" does here.

df <- data.frame(
x = 1:4,
y = 1:4,
colour = c("red", "green", "blue", "yellow")
ggplot(df, aes(x, y)) +
geom_tile(aes(fill = colour)) +
scale_fill_identity("trt", labels = letters[1:4], breaks = df$colour, guide = "legend")

I am a beginner and am struggling with ggplot2. I have bought Wickham's ggplot2 book and reading it. So, I thought of asking about it.

Thanks in advance.


In this example, the user just wanted to change the names of the colors in the legend. Each value color value in the data.frame is used as the fill color thanks to scale_fill_identity but in order to match up the colors to labels, it's safest to give the labels and breaks, the latter are the actually values used for the fill, and the former are how you want them described in the legend. So you are matching up

labels = c("a","b","c","d"),
breaks = c("red", "green", "blue", "yellow")

where the values at each position are matched up.

enter image description here