【问题标题】:R ggplot2: labels inside bars, no stacked geom_barR ggplot2:条内的标签,没有堆叠的geom_bar
【发布时间】:2020-09-07 11:32:59
【问题描述】:

我有以下数据集:

data <- structure(list(Q14 = c("< 5 people", "> 11 people", "6-10 people", 
NA), count = c(148L, 13L, 34L, 21L), var = c("Team Size", "Team Size", 
"Team Size", "Team Size")), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

我将 geom_bar 绘制如下:

library(ggplot2)
library(wesanderson)

ggplot(data) +
  geom_bar( aes(x = var, y = count, fill = Q14), stat = "identity", position = "fill") +
  coord_flip() + 
  theme(legend.position = "none", 
        axis.title.x=element_blank(), axis.title.y=element_blank()) +
  scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))

我想打印条内的标签,如下。注意:我的编辑技术很烂,我当然希望标签是对齐的,它们也可以逆时针旋转。

另一种选择是获得以下内容,我也很喜欢:

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    一种选择是使用geom_text

    ggplot(data, aes(x = var, y = count, fill = Q14, label = Q14)) +
      geom_bar(stat = "identity", position = "fill", ) +
      geom_text(position = position_fill(vjust = 0.5), size = 3) +
      coord_flip() + 
      theme(legend.position = "none", 
            axis.title.x=element_blank(),
            axis.title.y=element_blank()) +
      scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))
    

    另一种选择是使用来自ggrepelgeom_label_repel

    library(ggrepel)
    ggplot(data, aes(x = var, y = count, fill = Q14, label = Q14)) +
      geom_bar(stat = "identity", position = "fill", ) +
      geom_label_repel(position = position_fill(vjust = 0.5),
                       direction = "y",
                       point.padding = 1,
                       segment.size = 0.2, 
                       size = 3,
                       seed = 3) +
      coord_flip() + 
      theme(legend.position = "none", 
            axis.title.x=element_blank(),
            axis.title.y=element_blank()) +
      scale_fill_manual(values = wes_palette("Zissou1", 3, type = "continuous"))
    

    请注意,seed 参数设置每个标签走向的随机过程。如果您不喜欢我喜欢的号码,请选择其他号码。

    【讨论】:

    • 第二个选项很好,但问题是我拥有的类别(颜色)越多,而且条越细,看起来真的很乱。
    • 使用geom_label_repel的其他参数,特别是force = box.padding = direction = "both"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多