[英]Barplot in R with stacked columns and custom x axis labels
将这些条彼此相邻的是“躲避”条 plot,而不是“堆叠”条 plot,这意味着条位于彼此顶部。 在基础 R 中,您可以执行以下操作:
barplot(t(df), beside = TRUE, col = c("#4f81bd", "#c0504d"))
这是一个闪避的酒吧 plot。
如果您想要一个堆叠条 plot,它将是:
barplot(t(df), beside = FALSE, col = c("#4f81bd", "#c0504d"))
如果您想完全自定义所有图形元素,使用
ggplot
是一种更好的方法。 例如,如果你真的喜欢 MS Excel 看看:
library(tidyverse)
df %>%
as.data.frame() %>%
rownames_to_column() %>%
pivot_longer(-1) %>%
ggplot(aes(rowname, value, fill = name)) +
geom_col(position = position_dodge(width = 0.75), width = 0.5) +
theme_minimal(base_size = 16) +
scale_fill_manual(values = c("#4f81bd", "#c0504d"),
labels = c('Series1', 'Series2'), name = NULL) +
scale_y_continuous(breaks = 0:6, limits = c(0, 6), name = NULL) +
labs(x = NULL, title = 'Chart title') +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
legend.position = 'bottom',
plot.title = element_text(hjust = 0.5))
顺便说一句,使用基础 R 你需要制作一个矩阵并转置它才能正常工作......
names <- c("a","b","c","d")
val1 <- c(1,2,3,4)
val2 <- c(2,3,4,5)
df <- cbind(val1,val2)
rownames(df) <- names
barplot(t(as.matrix(df)), beside=TRUE)
我在上面错了:t() 与 dfs 配合得很好,所以不需要 as.matrix。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.