Home > OS >  R ggplot2 show.legend = FALSE not working
R ggplot2 show.legend = FALSE not working

Time:09-07

Based on the celsius data and code below, the plot is fine, it's just that show.legend = F is not working.

Why is that so?

I know this question has been asked previously, but I wanted to know to have an answer/comment in context to my code.

df =

    structure(list(CITYNAME = c("a", "b", "c", 
    "d", "e", "f", "g", 
    "h", "i", "j", "k", 
    "l", "m", "n", "p", "q", 
    "r", "s", "t", "u", 
    "w", "x", "y", "z"), AvgTMin = c(20.28, 
20.38, 20.08, 20.35, 20.38, 20.76, 21, 21.21, 20.45, 20.21, 21.18, 
20.29, 20.61, 20.44, 20.95, 19.75, 20.58, 20.32, 21.05, 20.28, 
20.09, 20.15, 20.73, 20.12)), row.names = c(NA, 
    -24L), class = c("tbl_df", "tbl", "data.frame"))

Code:

# Plot in Fahrenheit
df %>% mutate(AvgTMin = AvgTMin * (1.8)   32) %>% # Convert from C to F
      ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME))  
      geom_bar(stat="identity")  
      coord_cartesian(ylim = c(60,70.3))  
      theme(axis.text = element_text(size = 14))  
      geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4,
                show.legend = FALSE)  
      labs(x = NULL, y = "Avg. Min. Temperature \u00B0F")   
      theme(axis.text.x = element_text(angle = 90))  
      ggtitle("1980-2021 Temperature Trend By City")

CodePudding user response:

show.legend must be put inside geom_bar()

df %>% mutate(AvgTMin = AvgTMin * (1.8)   32) %>% # Convert from C to F
       ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME))  
       geom_bar(stat="identity", show.legend = F)  
       coord_cartesian(ylim = c(60,70.3))  
       theme(axis.text = element_text(size = 14))  
       geom_text(aes(label=sprintf("%0.2f", AvgTMin)), vjust=-0.2, size = 4)  
       labs(x = NULL, y = "Avg. Min. Temperature \u00B0F")   
       theme(axis.text.x = element_text(angle = 90))  
       ggtitle("1980-2021 Temperature Trend By City")
  • Related