Home > Enterprise >  Insert data of two columns in a graph legend - ggplot2
Insert data of two columns in a graph legend - ggplot2

Time:07-20

I have the following dataframe.

df <- data.frame(product = c("a", "b", "c", "d"),
                 count = c(3, 4, 6, 7),
                 name = c("ball", "pen", "notebook", "pencil"))

ggplot(df, aes(x = "", y = count, fill = product))  
  geom_bar(stat = "identity", width = 1)  
  coord_polar("y", start = 0)

Is it possible to make the legend with information of two columns? I mean, I would like to make it like: a - ball; b - pen; c - notebook; d - pencil.

enter image description here

I know I can merge the columns using stringr::str_c and make a new legend like this, but I would like to use a more elegant solution.

Thank you in advance.

CodePudding user response:

What you could do is combine the columns in one line using paste0 and assign these labels in scale_fill_discrete like this:

df <- data.frame(product = c("a", "b", "c", "d"),
                 count = c(3, 4, 6, 7),
                 name = c("ball", "pen", "notebook", "pencil"))

library(ggplot2)

ggplot(df, aes(x = "", y = count, fill = product))  
  geom_bar(stat = "identity", width = 1)  
  coord_polar("y", start = 0)  
  scale_fill_discrete(labels = with(df, paste0(product, " - ", name)))

Created on 2022-07-19 by the reprex package (v2.0.1)

  • Related