代码之家  ›  专栏  ›  技术社区  ›  Simon Harmel

ggplot2中显示的piechart标签不正确

  •  0
  • Simon Harmel  · 技术社区  · 1 年前

    我正试着拼凑我的 DATA 下面,但标签和颜色似乎放错了地方。

    是否有任何特定的设置来对齐标签和颜色?

    library(ggrepel)
    
    DATA <- read.table(header=T, text="
    EthnicCd    SchoolYear n_RCA percent  csum    pos
    Hispanic          2324  4520 50%      9117   6857  
    Asian             2324  1800 20%      4597   3697  
    White             2324  1737 19%      2797   1928. 
    Black             2324   447 5%       1060   836. 
    Pacific           2324   395 4%        613   416. 
    Multiracial       2324   203 2%        218   116. 
    AmerInd           2324    15 0%         15   7.5")
    
    
    ggplot(DATA, aes(x="", y=n_RCA, fill=EthnicCd)) +
      geom_bar(stat="identity", width=.008, color="white") +
      coord_polar("y", start = 5.5) +
      theme_void() +
      scale_fill_brewer(palette="Set1")+
      guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))+
      geom_label_repel(aes(y = pos, label = paste0(n_RCA,"\n(",percent,")")),
                       size = 3, nudge_x = .004, nudge_y=4,
                       show.legend = FALSE)
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Axeman    1 年前

    首先,您为两个层提供不同的y值。其次,默认情况下,条形图是堆叠的,但标签不是。我们需要提供 position 为了使标签与条的堆叠相匹配,我们可以使用justice参数将标签放置在条的一半:

    ggplot(DATA, aes(x = 1, n_RCA, fill=EthnicCd)) +
      geom_col(width = 1, color="white") +
      geom_label_repel(
        aes(x = 1.49, label = paste0(n_RCA,"\n(",percent,")")),
        position = position_stack(vjust = 0.5),
        size = 3,
        show.legend = FALSE
      ) +
      coord_polar("y", start = 5.5) +
      theme_void() +
      scale_fill_brewer(palette="Set1")+
      guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))
    

    我将标签的x位置设置为~1.5,这样它们就可以放在馅饼的外面。这是因为我设置 x = 1 对于条形图,条形图的“宽度”为1,因此其范围为0.5至1.5。

    极坐标有时会令人困惑,首先用笛卡尔坐标绘制通常会有所帮助,这样堆叠问题就会变得更加明显。

    enter image description here

    推荐文章