Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the gradient legend's scale to percentage with specific breaks

Tags:

r

ggplot2

I had a heat map with a gradient for which I wanted to label the legend at specific percentages.

# example data, apologies for the kludginess 
library('ggplot2'); library('scales'); require('dplyr');
as.data.frame(with(mtcars, table(gear, cyl))) %>% 
  group_by(cyl) %>%
  mutate(pct_of_cyl_class = Freq / sum(Freq)) %>%
  ggplot(. ,aes(cyl, gear)) + 
     geom_tile(aes(fill=pct_of_cyl_class)) +
     scale_fill_gradient(low='yellow',high='brown', name='% of Cyl. Group') +
     geom_text(aes(label=percent(pct_of_cyl_class))) +
     xlab('Cylinder Class') + ylab('Gears') +
     ggtitle('Gear Frequency by Cylinder Class') + theme_minimal()

enter image description here

like image 414
C8H10N4O2 Avatar asked Jan 07 '23 06:01

C8H10N4O2


1 Answers

I needed to set breaks and labels in scale_fill_gradient().

+ scale_fill_gradient(low='yellow',high='brown', 
                      name='% of Cyl. Group', 
                      breaks = 0.25*0:4, labels = percent(0.25*0:4) ) # <-

enter image description here

like image 108
C8H10N4O2 Avatar answered Jan 31 '23 10:01

C8H10N4O2