小编EBW*_*EBW的帖子

在ggplot2中的图例上的某些级别之间添加线条

我有一个这样的情节:

我的示例情节

这是一个马赛克图,其中一些组上方有一条黑线.我希望黑线也能成为传奇.在这个例子中,图例有6个级别,高于2级和4级的正方形,我想要一条黑线.

我尝试了类似的方法: 如何在ggplot2中绘制绘图区域以外的线条,但不幸的是,当我调整绘图大小时,线条会随着情节移动而不是传说,它们会在错误的位置移动.

以下是制作上图的示例代码.

exampledata<-data.frame(var1Center=c(rep(.2, 6) ,rep(.5,6) ,rep(.8,6)), 
                        var2Height=c(.2,.2,.2,.1,.1,.2, .1,.1,.05,.45,.1,.2,  .4,.07,.03,.1,.35,.05),
                        var1=c(rep("Thing 1", 6), rep("Thing 2", 6), rep("Thing 3", 6)),
                        var2=c( rep(c("A", "B", "C","D", "E", "F"), 3)), 
                        marginVar1=c(rep(.4,6) ,rep(.2,6), rep(.4,6)))

plotlines<-data.frame(xstart=c(0, 0,.4, .4, .6,.6), xstop=c(.4,.4, .6,.6, 1,1), value=c(.4, .7, .2,.7, .47, .6))

ggplot(exampledata, aes(var1Center, var2Height)) +
  geom_bar(stat = "identity", aes(width = marginVar1, fill = var2)) +
  scale_x_continuous(breaks=exampledata$var1Center, labels=exampledata$var1, expand=c(0,0))+
  theme_bw()+scale_y_continuous(name="Proportion",expand=c(0,0))+
  guides(fill = guide_legend(reverse=TRUE))+
  theme(panel.border=element_blank(), panel.grid=element_blank())+
  theme(axis.text.x=element_text(angle=90, hjust=1, vjust=.3))+
  geom_segment(data=plotlines, aes(x=xstart, xend=xstop, y=value, yend=value))
Run Code Online (Sandbox Code Playgroud)

r legend ggplot2

5
推荐指数
1
解决办法
183
查看次数

标签 统计

ggplot2 ×1

legend ×1

r ×1