ggplot2:连接坐标轴和点的线

5

数据:

df<-data.frame(grp=letters[1:4],perc=runif(4))

第一选项:

首先,创建一个包含每个组的零的第二个数据集

df2<-rbind(df,data.frame(grp=df[,1],perc=c(0,0,0,0)))

然后使用geom_pointsgeom_line进行绘图:

ggplot(df,aes(y=perc,x=grp))+
  geom_point()+
  geom_line(data=df2, aes(y=perc, x=grp))+
  coord_flip()

工作量过大_看起来不错

这看起来很好。只是创建第二个数据集需要太多额外的工作。

另一个选择是使用geom_bar并将宽度设置得很小:

ggplot(df,aes(y=perc,x=grp))+
  geom_point()+
  geom_bar(stat="identity",width=.01)+
  coord_flip()

奇怪的细条_在PDF中大小不一

但这也很奇怪,当我保存为.pdf时,并非所有的条都是同样的宽度。

显然应该有更简单的方法来做到这一点,有什么建议吗?

1个回答

6

使用带有固定 yend = 0geom_segment。您还需要使用expand_limits来调整绘图区域:

ggplot(df, aes(y=perc, x=grp)) +
    geom_point() +
    geom_segment(aes(xend=grp), yend=0) +
    expand_limits(y=0) +
    coord_flip()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接