我有这样的样本数据:
name <- rep(c("ba", "EW", "RW", "Se", "St", "US", "VN"), 2)
value <- c(0, 6323, 7397, 13945, 11801, 55255, 22519, 4124, 13540, 9616, 57724, 6646, 22021, 8841)
type <- c(rep("g", 7), rep("o", 7))
test <- data.frame(name, value, type)
并使用代码创建了一个绘图:
ggplot(test, aes(x=name, y=value, fill=type)) +
geom_bar(position = position_stack(reverse = TRUE), stat='identity') +
theme(plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = c("#0099f9", "#69c6ff")) +
geom_text(aes(label = value), position = position_stack(vjust = 0.5), colour = "black", size = 3) +
guides(fill = guide_legend(title = "", reverse = TRUE))
数据标签不在每个块中居中: 情节
我使用了在ggplot2中的堆积条形图上显示数据值和(R) ggplot2标签未正确居中中的解决方案,但是
position = position_stack(vjust = 0.5)
在 geom_text 中没有帮助
为什么会这样,我还能做什么?
编辑: 感谢 Stefan 纠正我的解决方案。 还有一个问题是我想添加另一个带有数据的 Y 轴:
name2 <- c("ba", "EW", "RW", "Se", "St", "US", "VN")
share <- c("100%", "61%", "47%", "80%", "34%", "28%", "28%")
test2 <- data.frame(name2, share)
所以基本上他们使用相同的x轴,份额是来自o型/(g型+o型)的百分比
我已经看到了关于双轴是否有意义的长时间讨论https://www.perceptualedge.com/articles/visual_business_intelligence/dual-scaled_axes.pdf 但我只需要它,我该如何使用 ggplot2 来做到这一点?
您也必须
reverse
标签的堆栈顺序,即使用position_stack(vjust = 0.5, reverse = TRUE)
作为geom_text
:
library(ggplot2)
ggplot(test, aes(x = name, y = value, fill = type)) +
geom_bar(position = position_stack(reverse = TRUE), stat = "identity") +
theme(plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values = c("#0099f9", "#69c6ff")) +
geom_text(aes(label = value),
position = position_stack(vjust = 0.5, reverse = TRUE),
colour = "black", size = 3
) +
guides(fill = guide_legend(title = "", reverse = TRUE))