rggplot2legendbreakgeom-tile

How to specify break points in legend for geom_tile plot?


I'm making a sort-of heat map using geom_tile, and I'm running into a small aesthetic issue with the legend. As is, I'm generating breaks in the legend using the number of levels in my data, and the plot looks great, but the breaks aren't equally spaced, and are non-integer valued.

enter image description here

Does anyone know how to write the breaks argument such that breaks in the legend are equally spaced and integer valued?

Here's my code:

# Fake data
Freq <- rep(1:13, 15)
SD <- c(rep(1, 13), rep(2, 13), rep(3, 13), rep(4, 13), rep(5, 13), rep(6, 13), rep(7, 13), rep(8, 13), rep(9, 13), rep(10, 13), rep(11, 13), rep(12, 13), rep(13, 13), rep(14, 13), rep(15, 13))
Intro_0 <- sample(80:120,195,TRUE)
test2 <- cbind(Freq, SD, Intro_0)

# Setting up colours
colours <- colorRampPalette(c("deeppink4", "violetred", "palevioletred", "rosybrown1"))(165)
test2$Intro_0 <- factor(test2$Intro_0)
N <- nlevels(test2$Intro_0)

# Plotting
ggplot(test2, aes(x = Freq, y = SD, fill = Intro_0))+
  geom_tile()+
  xlab("Frequency of Disturbance")+ 
  ylab("Magnitude of Disturbance")+
  labs(fill="Longevity")+
  scale_x_discrete(labels= c("Once every 10 days", " ", " ", "Once per week", " ", "Once every 5 days", " ", " ", "Once every 2 days", "Once per day", "Twice per day", " ", "10 times per day"))+
  scale_fill_manual(values=colours, breaks=levels(test2$Intro_0)[seq(1, N, by=30)])+
  #scale_fill_manual(values=colours, breaks=c(80, 90, 100, 110, 120))+
  theme_tufte()+
  theme(axis.text.x = element_text(angle = 45, hjust=1))

I've tried this:

scale_fill_manual(values=colours, breaks=c(80, 90, 100, 110, 120))

But the legend just disappeared?

Thanks so much for any help! 🙂


Solution

  • I suspect the problem is that your data are not continuous but are likely strings or factors


    It looks like the problem is with how you're defining your breaks. It's not really clear how you're coming up with the breaks?

    geom_tile() will automatically make the legend integer-based.

    I tried to reproduce your problem with some fake data:

    y = data.frame(value = sample(c(10.5273:100.727437), 300, replace = TRUE),
                   group1 = sample(c("op1", "op2", "op3", "op4", "op5", "op6"),
                                   300, replace = TRUE), 
                   group2 = sample(c("x1", "x2", "x3", "x4", "x5", "x6", "x7"),
                                   300, replace = TRUE))
    colours <- colorRampPalette(c("deeppink4", "violetred", 
                                  "palevioletred", "rosybrown1"))(165)
    ggplot(data = y, aes(x = group2, y = group1, fill = value)) + 
             geom_tile() 
    

    And it gives this with integer breaks enter image description here

    Could you use this fake data to try and reproduce the problem with the breaks so we can see what's going on?