Home > Net >  How to produce annotated monthly heatmap in R?
How to produce annotated monthly heatmap in R?

Time:05-20

I have a dataset similar as follows:

df <- structure(list(Topic = c("Topic_A", "Topic_A", 
                              "Topic_A", "Topic_A", "Topic_A", 
                              "Topic_A", "Topic_A", "Topic_A", 
                              "Topic_A", "Topic_A", "Topic_A", 
                              "Topic_B", "Topic_B", "Topic_B", 
                              "Topic_B", "Topic_B", "Topic_B", 
                              "Topic_B", "Topic_B", "Topic_B", 
                              "Topic_B", "Topic_B"), 
                    month = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
                                        11L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L), .Label = c("Jan", 
                                        "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 
                                        "Nov", "Dec"), class = c("ordered", "factor")), N = c(439L, 
                                        291L, 592L, 527L, 336L, 254L, 141L, 137L, 68L, 182L, 125L, 
                                        48L, 111L, 74L, 127L, 55L, 80L, 105L, 129L, 63L, 72L, 82L
                                        )), row.names = c(NA, 22L), class = "data.frame")

And I am using the following code to produce a monthly heatmap, month name on X-axis and Topic name on Y axis:

ggplot(df, aes( month,Topic))   geom_tile(aes(fill = N),colour = "white")  
  #scale_fill_gradient(low = col1, high = col2)    
  scale_fill_viridis(name="Hrly Temps C",option ="C") 
  guides(fill=guide_legend(title="Frequency"))  
  labs(title = "Topic Heatmap",
       x = "Month", y = "Topic")  
  theme_bw()   theme_minimal()   
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

Since in my original dataset, topic names are different for almost each month, I would like to annotate each box of heatmap with the topic name against its corresponding month, removing Y-axis in this scenario, and adding text inside the heatmap box for each month.

Any guidance how can I do that?

CodePudding user response:

You can add geom_text() to add a text to each panel, and remove the y axis value by using element_blank() in theme

ggplot(df, aes( month,Topic))   geom_tile(aes(fill = N),colour = "white")  
  #scale_fill_gradient(low = col1, high = col2)    
  scale_fill_viridis_c(name="Hrly Temps C") 
  guides(fill=guide_legend(title="Frequency"))  
  labs(title = "Topic Heatmap",
       x = "Month", y = "Topic")  
  theme_minimal()   
  geom_text( aes(x = month, y = Topic, label = Topic), angle = 90, color = "white")   
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.text.y = element_blank()) 
  • Related