[英]Conditonally add labels to ggplot stacked barplot
This is similar to previous questions, but I haven't found a solution that works yet. 这与之前的问题类似,但是我还没有找到可行的解决方案。
I have a stacked barplot in ggplot almost exactly like the one listed here . 我在ggplot中有一个堆积的barplot,几乎和这里列出的一样。 Like that user, I only want category labels for those bars with a count > 20. I tried to do the subset solution suggested there as well as an ifelse statement.
像那个用户一样,我只想要计数> 20的那些条的类别标签。我尝试执行此处建议的子集解决方案以及ifelse语句。 For the subset solution I get:
对于子集解决方案,我得到:
Error in n > 20 : comparison (6) is possible only for atomic and list types
My graph: 我的图:
data %>%
count(groups, Response) %>%
mutate(group = factor(groups)) %>%
ggplot(aes(groups, n, fill=Response)) +
geom_col(aes(fill = Response)) +
geom_text(data=subset(data, n>20), aes(label=n), position=position_stack(0.5), size = 3)
I don't know if sharing my data would be useful, but I can do that if necessary. 我不知道共享数据是否有用,但是如有必要,我可以这样做。
Your data
does not contain n
, only your piped in anonymous data does, after the count
function. 在
count
函数之后,您的data
不包含n
,仅管道传输的匿名数据包含n
。 Here are three solutions: 这是三个解决方案:
1. 1。
data %>%
count(groups, Response) %>%
mutate(group = factor(groups)) %>%
{
ggplot(., aes(groups, n, fill=Response)) +
geom_col(aes(fill = Response)) +
geom_text(data=filter(., n>20), aes(label=n), position=position_stack(0.5), size = 3)
}
2. 2。
counts <- data %>%
count(groups, Response) %>%
mutate(group = factor(groups))
ggplot(counts, aes(groups, n, fill=Response)) +
geom_col(aes(fill = Response)) +
geom_text(data=filter(counts, n>20), aes(label=n), position=position_stack(0.5), size = 3)
3. 3。
data %>%
count(groups, Response) %>%
mutate(group = factor(groups)) %>%
ggplot(aes(groups, n, fill=Response)) +
geom_col(aes(fill = Response)) +
geom_text(data=. %>% filter(n>20), aes(label=n), position=position_stack(0.5), size = 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.