基于单个DataFrame绘制并列双条形图的格式问题
双条形图并列显示失败的解决办法
问题详情
想让两组条形并列显示而非堆叠,但用position_dodge实现失败。使用的DataFrame(combinedCountFrame)如下:
system n.x n.y 1 T-64BV 7 65 2 T-72A 8 0 3 T-72AV 3 2 4 T-72B 47 2 5 T-72B Obr. 1989 13 0 6 T-72B3 30 0 7 T-72B3 Obr. 2016 70 0 8 T-80BV 11 3 9 T-80BVM 18 0 10 T-80U 44 0 11 T-80UK 2 0 12 T-80UM2 1 0 13 T-90A 17 0 14 Unknown tank 25 1 15 T-64B1M 0 1 16 T-72AMT 0 3
绘图代码:
ggplot(combinedCountFrame, aes(x = system)) + geom_bar(aes(y = n.x, fill = "Russia"), stat = "identity", position = position_dodge(width = 0.8)) + geom_bar(aes(y = n.y, fill = "Ukraine"), stat = "identity", position = position_dodge(width = 0.8)) + labs( title = paste(equipmentType, "Losses", sep = " "), y = "# of Systems Lost", fill = "Country" ) + theme_minimal() + theme( legend.position = "top", axis.text.x = element_text(angle = 45, hjust = 1) )
生成的图表中条形是堆叠状态,没有实现并列。
解决方法
问题根源在于你的数据是宽格式,而ggplot绘制分组条形图需要长格式数据。先转格式再绘图即可解决:
1. 转换数据格式
用tidyr包的pivot_longer把宽表转成长表:
library(tidyr) library(dplyr) long_df <- combinedCountFrame %>% pivot_longer( cols = c(n.x, n.y), names_to = "Country", values_to = "Losses", names_prefix = "n." ) %>% mutate(Country = ifelse(Country == "x", "Russia", "Ukraine"))
2. 绘制并列条形图
用转换后的长数据绘图,只需要一组geom_bar,并在aes里指定fill = Country,配合position_dodge:
ggplot(long_df, aes(x = system, y = Losses, fill = Country)) + geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) + labs( title = paste(equipmentType, "Losses", sep = " "), y = "# of Systems Lost", fill = "Country" ) + theme_minimal() + theme( legend.position = "top", axis.text.x = element_text(angle = 45, hjust = 1) )
关键说明
- 宽转长是ggplot处理分组图的标准流程,这样ggplot能明确每个分组对应的数值,自动处理并列逻辑。
position_dodge(width = 0.8)控制两组条形的间距,width = 0.7控制单条条形的宽度,可根据视觉效果调整。
内容的提问来源于stack exchange,提问作者Scipio
相关产品推荐
相关产品推荐

