[英]Issue using position dodge vertically in ggplots with geom_linerange in R
[英]How to make geom_linerange dodge position according to geom_point
我正在尝试使用我在 R 中生成的理论数据创建一个点 plot。在 x 轴上,我有四个类别(1、2、3、4),在 y 轴上,我有每个 x 类别的一些预测。 这就是我创建数据的方式:
x<-c(1,2,3,4,1,2,3,4)
conf.low<- c(0.65, 0.65, 0.15, 0.15, 0.65, 0.15, 0.65, 0.40)
predicted<-c(0.70, 0.70, 0.20, 0.20, 0.70, 0.20, 0.70,0.45)
conf.high<-c(0.75, 0.75, 0.25, 0.25, 0.75, 0.25, 0.75, 0.50)
group2<- c("Day","Day","Day","Day","Night","Night","Night","Night")
tot.risk<-cbind.data.frame(x, predicted, conf.low, conf.high, group2) #Combine all the variables
tot.risk$group2<-as.factor(tot.risk$group2)
tot.risk$x<-factor(tot.risk$x, levels = c(1:4), labels = c("Double low", "Low hunt/high wolf",
"High hunt/low wolf", "Double high"))
#Plot it
ggplot(tot.risk, aes(x = x, y = predicted)) +
scale_fill_manual(values=c("white", "black"))+
geom_point(pch=21, size=6, aes(fill=group2), position = position_dodge(width = 0.8))+
scale_y_continuous(limits = c(0,0.8))+
geom_linerange(aes(ymin=conf.low, ymax=conf.high), position = position_dodge(width = 0.8))+
theme_classic()+
theme(axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size=12),
axis.title.x = element_text(size=14),
axis.title.y = element_text(size=14),
legend.text = element_text(size=14),
legend.title = element_blank())+
xlab("Type of risk")+
ylab("Probability of selection") ````
这是我在运行此代码时得到的 plot: 正如你所看到的, geom_linerange
并没有与点一起闪避。 我不知道如何解决这个问题。 有没有人知道position_dodge
在这种情况下不起作用?
您可以使用position_dodge2()
来获得正确的“闪避”。
从文档中:
position_dodge() 需要在全局或 geom_* 层中指定分组变量。 与 position_dodge() 不同,position_dodge2() 在图层中没有分组变量。
因此,如果您想使用position_dodge
,请将fill = group2
放入ggplot(aes())
或直接在geom_linerange
中使用position_dodge2
。
library(ggplot2)
ggplot(tot.risk, aes(x = x, y = predicted)) +
scale_fill_manual(values=c("white", "black"))+
geom_point(pch=21, size=6, aes(fill=group2), position = position_dodge(width = 0.8))+
scale_y_continuous(limits = c(0,0.8))+
geom_linerange(aes(ymin=conf.low, ymax=conf.high), position = position_dodge2(width = 0.8))+
theme_classic()+
theme(axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(size=12),
axis.title.x = element_text(size=14),
axis.title.y = element_text(size=14),
legend.text = element_text(size=14),
legend.title = element_blank())+
xlab("Type of risk")+
ylab("Probability of selection")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.