Home > Software engineering >  How can I add both x and y values in the legend of my ggplot bargraph?
How can I add both x and y values in the legend of my ggplot bargraph?

Time:02-25

My code currently looks like this:

bd <- ggplot(data=cases_locations,
             aes(x= reorder(NAME, -COUNT),y=COUNT,fill=NAME))  
      geom_bar(stat="identity")

bd   theme(legend.position = "bottom",
           legend.justification = "left",
           legend.direction="vertical",
           legend.text = element_text())  
      labs(fill="Cases",
           title="Cases",
           y="Number of Cases",x="Name")

What I can't figure out is how to create a legend that lists every x value and then also its associated y value. I can't enter these values manually because I am using data that changes daily and need a plot that updates automatically. Right now my legend displays only the x value.

Technically I could make a separate table to do what I want to do however I want the colors of my table symbols to correspond with the colors represented on my bar graph. So ideally the legend of the bar graph has all the information I want to represent.

CodePudding user response:

You can paste the names and counts together for the fill aesthetic:

ggplot(cases_locations,
       aes(x    = reorder(NAME, -COUNT), 
           y    = COUNT, 
           fill = reorder(paste(NAME, COUNT, sep = " : "), -COUNT)))  
      geom_col()  
      theme(legend.position      = "bottom",
            legend.justification = "left",
            legend.direction     = "vertical",
            legend.text          = element_text())  
      labs(fill                  = "Cases",
           title                 = "Cases",
           y                     = "Number of Cases",
           x                     = "Name")

enter image description here


Data used

cases_locations <- data.frame(
  NAME = c("Narnia", "Middle-Earth", "Hammerfell", "Never-Never Land"),
  COUNT = c(2034, 576, 896, 167)
  )
  • Related