代码之家  ›  专栏  ›  技术社区  ›  Honorato

在图形图例中插入两列数据-ggplot2

  •  0
  • Honorato  · 技术社区  · 2 年前

    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)
    

    可以用两列的信息制作图例吗?我的意思是,我想把它变成:一个球;b-笔;c-笔记本;d-铅笔。

    enter image description here

    我知道我可以使用stringr::str\u c合并列并创建这样的新图例,但我希望使用更优雅的解决方案。

    提前谢谢你。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Quinten    2 年前

    paste0 并在中指定这些标签 scale_fill_discrete 这样地:

    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)))
    

    reprex package