简体   繁体   English

R ggplot2:标签在条内,没有堆叠的geom_bar

[英]R ggplot2: labels inside bars, no stacked geom_bar

I have the following dataset:我有以下数据集:

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

And I plot my geom_bar as follows:而我 plot 我的 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"))

I would like to print the labels inside the bar, as follows.我想在栏内打印标签,如下所示。 Note: my editing skills suck, I'd like labels to be aligned of course, and they can be rotated CCW as well.注意:我的编辑技巧很烂,我当然希望标签对齐,它们也可以逆时针旋转。

在此处输入图像描述

Another option is to obtain something as follows, which I also like:另一种选择是获得以下内容,我也喜欢:

在此处输入图像描述

One option is to use geom_text :一种选择是使用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"))

在此处输入图像描述

Another option is to use geom_label_repel from ggrepel :另一种选择是使用geom_label_repelggrepel

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

在此处输入图像描述

Note that the seed parameter sets the random process of which direction each label goes.注意seed参数设置每个label走向哪个方向的随机过程。 If you don't like the same one I do, pick a different number.如果您不喜欢我喜欢的号码,请选择其他号码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM