Lemon_land
Lemon_land

Reputation: 23

How to add expression to label in ggplot

I have been able add a facet based label, however, how do I make it label as the text:

"Mean = 0.235" instead of just "0.235"

Here's my ggplot, where the important part is geom_text:

ggplot(data = filter(season_melt,(HOUSEHOLD_ID_ANONYMISED %in% c(37218002754,37218032412, 38443537620))), aes(factor(HOUSEHOLD_ID_ANONYMISED), value)) + 
geom_boxplot(aes(fill = factor(HOUSEHOLD_ID_ANONYMISED))) + 
facet_wrap(~Season) + 
theme(text = element_text(size=40), legend.position = "none") + 
xlab("Household ID") + 
ylab("Usage") + 
geom_hline(data = mean_season, aes(yintercept = Mean), size = 1, colour = "blue", linetype = "dashed") + 
geom_text(data = mean_season, aes(0,Mean,label = round(Mean,3),  vjust = -1, hjust = -0.1), color = "blue", size = 11)

Here's a pic which shows the labels in each facet: enter image description here

Upvotes: 2

Views: 1837

Answers (1)

mnel
mnel

Reputation: 115392

You have (at least) two options.

  1. Create the appropriate character string

    # Something like
    geom_text(data = mean_season, 
           aes(0, Mean, label = sprintf('Mean = %0.3f', Mean),
               vjust = -1, hjust = -0.1),
           color = "blue", size = 11)
    # or
          geom_text(data = mean_season, 
           aes(0, Mean, label = paste('Mean = ',round(Mean, 3)),
               vjust = -1, hjust = -0.1),
           color = "blue", size = 11)
    
  2. Use parse=TRUE in the call to geom_text. In this case you would need to construct an appropriate expression according to ?plotmath (and ?geom_text)

      geom_text(data = mean_season, parse = TRUE
           aes(0, Mean, label = paste('Mean ==',round(Mean, 3)),
               vjust = -1, hjust = -0.1),
           color = "blue", size = 11)
    

Option 2 will create a "nicer" looking expression when visualized.

Upvotes: 4

Related Questions