Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot add text inside each tile of geom tile

Tags:

r

ggplot2

With dataframe df below

df <- data.frame(
  model=c(rep('corolla',3),rep( 'accord',3), rep('sunny',3)),
  variable=c('urban_mileage', 'rural_mileage', 'highway_mileage'),
  rescale=rnorm(9),
  year=c(rep(1998,3),rep( 1997,3), rep(2003,3)),
  kmdone=sample(10:100,9)*1e3
  )
> df
    model        variable     rescale year kmdone
1 corolla   urban_mileage -1.03675182 1998  56000
2 corolla   rural_mileage  1.06079162 1998  83000
3 corolla highway_mileage -0.18808551 1998  19000
4  accord   urban_mileage -0.05151496 1997  69000
5  accord   rural_mileage  0.05219512 1997  54000
6  accord highway_mileage -2.03139240 1997  21000
7   sunny   urban_mileage -0.06225862 2003  40000
8   sunny   rural_mileage  1.38191440 2003  96000
9   sunny highway_mileage -1.02367124 2003  55000
> 

I'm creating a heatmap using geom_tile as follows

ggplot(df, aes(variable, model)) + geom_tile(aes(fill = rescale), colour = "white") +
     scale_fill_gradient2(low = "red", mid = "white", high = "green") +
     labs(x = "",y = "") +
     theme(legend.title = element_blank(),
           axis.text.x = element_text(angle=30,hjust=1,vjust=1.0),
           axis.text.y = element_text(size = 12))

This gives a heat-map representation of mileage by road type as shown in the image at the end.

I need to enhance this with two things

  1. Add year as label for each model on the right-axis (secondary y-axis - though it is frowned upon :) )
  2. show kmdone values inside each tile as in the df - centered text with black color

enter image description here

like image 969
user3206440 Avatar asked Jul 17 '17 14:07

user3206440


2 Answers

Two small modifications... use paste(model,year) for the y aesthetic, and add a geom_text as shown...

ggplot(df, aes(variable, paste(model,year))) + geom_tile(aes(fill = rescale), colour = "white") + 
  geom_text(aes(label=kmdone)) +
  scale_fill_gradient2(low = "red", mid = "white", high = "green") +
  labs(x = "",y = "") +
  theme(legend.title = element_blank(),
        axis.text.x = element_text(angle=30,hjust=1,vjust=1.0),
        axis.text.y = element_text(size = 12))

enter image description here

like image 138
Andrew Gustar Avatar answered Nov 04 '22 14:11

Andrew Gustar


1. ggplot will fight you all the way if you try to make a secondary axis but you can try the approach here

2. Just:

... + geom_text(aes(label = kmdone))
like image 2
Eumenedies Avatar answered Nov 04 '22 14:11

Eumenedies