user3206440
user3206440

Reputation: 5059

ggplot geom_tile add custom labels

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)))

> df
    model        variable     rescale year
1 corolla   urban_mileage -0.73386453 1998
2 corolla   rural_mileage  0.21467425 1998
3 corolla highway_mileage -1.75450160 1998
4  accord   urban_mileage -0.08467004 1997
5  accord   rural_mileage -1.60112730 1997
6  accord highway_mileage  2.26943695 1997
7   sunny   urban_mileage  0.31349626 2003
8   sunny   rural_mileage -0.32768735 2003
9   sunny highway_mileage -0.04645053 2003

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. However I want to add year along with the current y-axis tick mark labels as text below the model name in brackets - i.e instead of the current y-axis tick mark labels it shall instead show

sunny
(2003)

corolla
(1998)

accord
(1997)

enter image description here

Upvotes: 1

Views: 3332

Answers (1)

timfaber
timfaber

Reputation: 2070

Something like this:?

ggplot(df, aes(variable, model)) + geom_tile(aes(fill = rescale), colour = "white") +
  scale_fill_gradient2(low = "red", mid = "white", high = "green") +
  labs(x = "",y = "") + scale_y_discrete(labels=paste(unique(df$model),paste0("(",unique(df$year),")"),sep="\n")) +
  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

Upvotes: 1

Related Questions