我正在尝试对齐群集条形图中每个条形的百分比频率。现在,我的图表如下所示:
这也是代码:
ggplot(graph_data, aes(x, Freq)) +
geom_bar(aes(fill = Pref), position = 'dodge', stat = 'identity') +
geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))),
hjust = -0.25) +
labs(list(x = attr(graph_data, 'seg_label'),
y = 'Frequency',
title = paste('Q:', attr(graph_data, 'question')))) +
scale_y_continuous(limits = c(0, 1.2 * max(graph_data$Freq))) +
guides(fill = F) +
coord_flip() +
annotate("text", x = Inf, y = Inf,
label = paste0("N = ", sum(graph_data$Freq)),
hjust = 1.5, vjust = 1.5)
我认为可以通过以下代码段解决此问题,但是我不确定如何:
geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))), hjust = -0.25)
任何帮助将不胜感激!
编辑:这也是我的数据结构的示例:
df <- data.frame(x = rep(c('1824', '2534', '3544'), 3),
Pref = rep(c('low', 'neutral', 'high')),
Freq = 1:9 * 10)
如评论中所述,我认为这是躲避barplot上的position geom_text的副本。
但是我现在做到了,所以我将包含代码。
ggplot(df, aes(x, Freq, fill = Pref)) +
geom_bar(position = 'dodge', stat = 'identity') +
geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))),
position = position_dodge(width = 0.9), hjust = -0.25) +
labs(list(x = attr(df, 'seg_label'),
y = 'Frequency',
title = paste('Q:', attr(df, 'question')))) +
scale_y_continuous(limits = c(0, 1.2 * max(df$Freq))) +
guides(fill = F) +
coord_flip()
您需要放入fill
原件,aes
这样才能geom_text
知道以哪个数量躲避哪个标签。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句