【发布时间】:2016-10-04 02:47:46
【问题描述】:
我有同样的问题,这里解释了Bars in geom_bar have unwanted different widths when using facet_wrap 也就是说,在刻面时,我的条形显示不同的宽度。我已经尝试过那里提出的解决方案,但似乎我做错了,因为我的条形重叠。我不是高级 R 用户,所以任何解释都将不胜感激。
我的代码:
# Data
z <- rbind.data.frame(c(23.230077, 109.824940, 72.313763, 76.95888),
c(29.154963, 113.716729, 94.689684, 64.29041),
c(8.450325, 99.190459, 53.193431, 32.97232),
c(15.719120, 126.947621, 39.767791, 56.8059),
c(15.497960, 117.942545, 73.659386, 69.37012),
c(13.522866, 9.939251, 5.906541, 27.69283))
colnames(z) <- c("Biomass", "Metals", "Other minerals", "Fossil fuels")
rownames(z) <- c("Exiobase full", "Exiobase global", "Exiobase EU","ENVIMAT", "ENVIMAT corrected", "Direct Imports")
library(ggplot2)
library(reshape2)
library(plyr)
z1 <- melt(as.matrix(z)); z2 <- c(rep(c(rep("Exiobase", 3), rep("Envimat",2), "Direct"),4))
z3 <- cbind.data.frame(z1, z2)
colnames(z3) <- c("Model", "Material", "Value", "Version")
# Here from the solution posted
N <- ddply(z3, .(Version), function(x) length(row.names(x)))
N$Fac <- N$V1 / max(N$V1)
z4 <- merge(z3, N[,-2], by = c("Version"))
# Plotting
fig3 <- ggplot(data=z4, aes(x=Version, y=Value ,fill=Model))+
geom_bar(aes(width = 1.5*Fac),stat="identity", position=position_dodge())+ scale_fill_brewer(palette="Set2")+ ylab("Million Tons")+
geom_text(aes(label = sprintf("%.1f",round(Value, 1), size=10)), position=position_dodge(width=0.9), vjust=-0.25)+
theme_bw()+theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(colour="grey", linetype = "dotted"),axis.title.x = element_blank(),legend.title=element_blank(), panel.background = element_rect(colour = "black"),legend.key=element_blank(),legend.text = element_text(colour="black"), strip.background = element_blank())+
facet_wrap(~Material, nrow=2)
plot(fig3)
非常感谢!
然后,如果我按照建议使用 BarWidth 和 DodgeWith 作为对原始问题的回答,我将无法控制条形组的闪避宽度。也就是说,我想将它们中的一些保持在一起,如下所示的两个“Envimat”栏。我改变了颜色,所以两个紫色条和三个红橙色条应该保持在一起。 新代码:
BarWidth = 0.75
DodgeWidth = .5
fig3 <- ggplot(data=z4, aes(x=Version, y=Value ,fill=Model))+
geom_bar(aes(width = BarWidth*Fac),stat="identity", position=position_dodge(width = DodgeWidth))+
ylab("Million Tons")+
geom_text(aes(label = sprintf("%.1f",round(Value, 1))), size=2,
position=position_dodge(width=DodgeWidth), vjust=-0.25)+
scale_fill_manual(values=c("#fdcc8a", "#fc8d59", "#d7301f", "#b3cde3","#8c96c6", "#c2e699"))+
theme_bw()+theme(panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(colour="grey", linetype = "dotted"),
axis.title.x = element_blank(),legend.title=element_blank(),
panel.background = element_rect(colour = "black"),
legend.key=element_blank(),
legend.text = element_text(colour="black"),
strip.background = element_blank())+
facet_wrap(~Material, nrow=2)
plot(fig3)
现在的问题(在红橙色条中,我想控制绿色和紫色条之间的距离): red-orange bars overlapped
如果我解决了红橙色条的问题,紫色条会被分开
BarWidth = 0.75
DodgeWidth = .75
非常感谢
【问题讨论】: