在ggplot2中,我想控制条形图或交叉图中变量和因子内的多个位置躲避。例如:
data = data.frame(Var=c("a","a","a","a","b","b","b","b"),
Val=c(0.5,0.4,0.1,0.0,-0.1,-0.3,-0.0,0.1),
g1=c(1,2,3,4,5,6,7,8),
g2=c(1,2,3,4,1,2,3,4),
g3=c(1,2,1,2,1,2,1,2))
q = ggplot(data,aes(Var,Val,ymin = Val-0.15,
ymax=Val+0.15,
group=g1,
colour=factor(g2),
fill=factor(g2),
linetype=factor(g3),))
q + geom_crossbar(width=0.5,fatten=2,size=0.5,position=position_dodge(width=0.51)) +
coord_flip() +
theme_bw() +
scale_fill_manual(values=c("#00000090","#00000090","#00000050","#00000050")) +
scale_colour_manual(values=c("#000000","#00000070","#000000","#00000070"))
在上面的示例中,我希望能够将较暗的条与较亮的条稍微分开,同时将每个条设置在一起。我可以实现多个位置躲避功能吗?任何帮助,将不胜感激。
最佳答案
我建议使用facet_grid
模拟所需的嵌套躲避。为此,我创建了一个新的g4
来对浅灰色和深灰色条进行分组。
library(ggplot2)
dat = data.frame(Var=c("a","a","a","a","b","b","b","b"),
Val=c(0.5,0.4,0.1,0.0,-0.1,-0.3,-0.0,0.1),
g1=c(1,2,3,4,5,6,7,8),
g2=c(1,2,3,4,1,2,3,4),
g3=c(1,2,1,2,1,2,1,2))
dat$g4 = c(1, 1, 2, 2, 1, 1, 2, 2) # New grouping factor
fill_values = c("#00000090","#00000090","#00000050","#00000050")
colour_values = c("#000000","#00000070","#000000","#00000070")
#---------------------------------------------------------------------------
fig1 = ggplot(dat, aes(x=Var, y=Val, ymin=Val - 0.15, ymax=Val + 0.15,
colour=factor(g2), fill=factor(g2), linetype=factor(g3))) +
geom_crossbar(width=0.5, fatten=2, size=0.5,
position=position_dodge(width=0.51)) +
coord_flip() +
theme_bw() +
scale_fill_manual(values=fill_values) +
scale_colour_manual(values=colour_values) +
opts(title="Figure 1: Original Version")
png("fig1.png", height=600, width=600)
print(fig1)
dev.off()
#---------------------------------------------------------------------------
fig2 = ggplot(dat, aes(x=factor(g4), y=Val, ymin=Val - 0.15,ymax=Val + 0.15,
colour=factor(g2), fill=factor(g2), linetype=factor(g3))) +
geom_crossbar(width=0.7, fatten=2, size=0.5,
position=position_dodge()) +
coord_flip() +
theme_bw() +
scale_fill_manual(values=fill_values) +
scale_colour_manual(values=colour_values) +
facet_grid(Var ~ .) +
opts(title="Figure 2: Proposed Solution")
png("fig2.png", height=600, width=600)
print(fig2)
dev.off()