应用权重后ggplot中的标签
Posted
技术标签:
【中文标题】应用权重后ggplot中的标签【英文标题】:Labels in ggplot after applying weights 【发布时间】:2021-08-30 23:54:06 【问题描述】:我绘制了一个包含权重的条形图,但是当我想为列添加标签时,会考虑一个没有权重的直方图。我必须使用 after_stat 参数吗?不知道如何正确使用?感谢您的帮助!
g <- ggplot(Y, aes(x=Q6, fill=Q3))
g + geom_bar()
g + geom_bar(aes(weight = XU$Q2), position="dodge", na.rm=TRUE)
g + geom_text(stat = "count", aes(label = after_stat(count)), vjust = -1)
structure(list(data = structure(list(Q6 = c("red", "red", "blue",
"green", "green", "green", "red", "red", "red", "grey", "purple",
"white", "black", "black", "black", "black", "black"), Q3 = c(1L,
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L
), Q2 = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, -17L
)), layers = list(), scales = <environment>, mapping = structure(list(
x = ~Q6, fill = ~Q3), class = "uneval"), theme = list(),
coordinates = <environment>, facet = <environment>, plot_env =
<environment>,
labels = list(x = "Q6", fill = "Q3")), class = c("gg", "ggplot"
))
【问题讨论】:
如果您可以在问题中包含您尝试绘制的数据或其中的样本,这将很有帮助。您可以为此目的使用dput
命令:)
嘿,我用示例数据更新了问题。
【参考方案1】:
我不太确定你想要展示什么,但也许你可以使用这种策略。首先,我将数据集转换为每个Q6
有一行,取每组各个行的总和。然后我可以像这样使用geom_col
和geom_text
library(tidyverse)
data = structure(list(Q6 = c("red", "red", "blue",
"green", "green", "green", "red", "red", "red", "grey", "purple",
"white", "black", "black", "black", "black", "black"), Q3 = c(1L,
1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L
), Q2 = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA, -17L
))
data %>%
group_by(Q6) %>%
summarise(Q3 = sum(Q3), Q2 = sum(Q2)) %>%
ggplot(aes(x=Q6, y=Q2, fill=Q3)) +
geom_col() +
geom_text(aes(label = Q2, group = Q6), vjust = -.2)
【讨论】:
以上是关于应用权重后ggplot中的标签的主要内容,如果未能解决你的问题,请参考以下文章