【问题标题】:How to change legend values on ggplot pie chart?如何更改ggplot饼图上的图例值?
【发布时间】:2020-08-12 19:55:44
【问题描述】:

我在 R 中构建了这个特殊的表格,以使用 ggplot 包构建饼图。

column,value,proportion,ypos,end,start,middle,hjust,vjust,legend
Urban,268053,97.78067170794165,48.890335853970825,6.143740798014896,0,3.071870399007448,0,1,Urban - 97.78 %
Rural,1296,0.4727563225686427,98.01704986922597,6.173444953813291,6.143740798014896,6.158592875914094,1,0,Rural - 0.47 %
Suburban,4788,1.746571969489708,99.12671401525515,6.283185307179586,6.173444953813291,6.228315130496439,1,0,Suburban - 1.75 %

但是,我希望在图例中打印图例列中的所有值,而不是列中的列,因为如果我决定在饼图中标记图例变量,它们就会过于拥挤。我也想更改图例标题。

以下是我用来构建此图表的代码。

library(ggplot2)
library(readr)
library(readxl)

demographics <- read_csv("C:\\path to file\\demographics.csv")

ggplot(demographics) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = column)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_color_manual(name = "Community Type", labels = c(legend)) +
  ggtitle("Percentage of Population by Type of Community")

有人可以帮助我吗?提前致谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    试试这个:

    library(ggplot2)
    library(readr)
    library(readxl)
    library(ggforce)
    
    ggplot(demographics) + 
      geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                       start = start, end = end, fill = legend)) +
      coord_fixed() +
      scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                         name = "", breaks = NULL, labels = NULL) +
      scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                         name = "", breaks = NULL, labels = NULL) +
      scale_color_manual(name = "Community Type", labels = c(legend)) +
      ggtitle("Percentage of Population by Type of Community")+
      guides(fill=guide_legend(title="New Legend Title"))
    

    输出:

    【讨论】:

    • 为我工作!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2022-01-07
    • 2021-03-15
    • 2021-12-27
    相关资源
    最近更新 更多