Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert data of two columns in a graph legend – ggplot2

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading