繁体   English   中英

ggplot2 和一组抖动/闪避点

[英]ggplot2 and jitter/dodge points by a group

我有“海拔”作为我的 y 轴,我希望它作为一个离散变量(换句话说,我希望每个海拔之间的空间相等,而不是相对于数值差异)。 我的 x 轴是“时间”(朱利安日期)。

    mydata2<- data.frame(
                   "Elevation" = c(rep(c(1200),10),rep(c(1325.5),10),rep(c(1350.75),10), rep(c(1550.66),10)),
                   "Sex" = c(rep(c("F","M"),20)),
                   "Type" = c(rep(c("emerge","emerge","endhet","endhet","immerge","immerge","melt","melt", "storpor","storpor"),4)),
                   "mean" = c(rep(c(104,100,102,80,185,210,84,84,188,208,104,87,101,82, 183,188,83,83,190,189),2))
                   "se"=c(rep(c(.1,.01,.2,.02,.03),4)))

mydata2$Sex<-factor(mydata2$Sex))
mydata2$Type<-factor(mydata2$Type))
mydata2$Elevation<-factor(mydata2$Elevation))

at<-ggplot(mydata2, aes(y = mean, x = Elevation,color=Type, group=Sex)) +
  geom_pointrange(aes(ymin = mean-se, ymax = mean+se), 
                  position=position_jitter(width=0.2,height=.1), 
                  linetype='solid') +
  facet_grid(Sex~season,scales = "free")+
  coord_flip()

at

在此处输入图片说明

理想情况下,我希望每个“类型”都垂直分开。 当我只抖动或躲避那些紧密分开且不均匀的那些时。 有没有办法强制每个“类型”稍微移动,以便它们都在自己的线上? 我试图通过给每种类型一个略有不同的“高度”来强制它,但最终我得到了一个凌乱的 y 轴(我想不出一种方法来保持这个点,但不显示具有离散比例的所有刻度线)。

感谢您的帮助。

如果要将数值用作离散值,则应使用as.factor 在您的示例中,尝试使用x = as.factor(Elevation)

此外,我会建议使用position = position_dodge()来从不同条件下获取对应于相同海拔的点并排绘制

ggplot(mydata2, aes(y = mean, x = as.factor(Elevation),color=Type, group=Sex)) +
  geom_pointrange(aes(ymin = mean-se, ymax = mean+se), 
                  position=position_dodge(), 
                  linetype='solid') +
  facet_grid(Sex~season,scales = "free")+
  coord_flip()

使用 OP 提供的示例数据进行编辑

使用您的数据集,我无法根据您的观点绘制范围。 因此,我使用dplyr包创建了两个变量LowerUpper

然后,我没有通过您在问题中提供的 commdnas facotr(...)而是使用as.factor(Elevation)position_dodge(0.9)进行绘图以获得以下图:

library(tidyverse)
mydata2 %>% mutate(Lower = mean-se*100, Upper = mean+se*100) %>%
  ggplot(., aes( x = as.factor(Elevation), y = mean, color = Type))+
  geom_pointrange(aes(ymin = Lower, ymax = Upper), linetype = "solid", position = position_dodge(0.9))+
  facet_grid(Sex~., scales = "free")+
  coord_flip()

在此处输入图片说明

它看起来像您要找的东西吗?

数据您提供的数据集包含的错误很少(括号过多),因此我在这里更正。

mydata2<- data.frame(
  "Elevation" = c(rep(c(1200),10),rep(c(1325.5),10),rep(c(1350.75),10), rep(c(1550.66),10)),
  "Sex" = rep(c("F","M"),20),
  "Type" = rep(c("emerge","emerge","endhet","endhet","immerge","immerge","melt","melt", "storpor","storpor"),4),
  "mean" = rep(c(104,100,102,80,185,210,84,84,188,208,104,87,101,82, 183,188,83,83,190,189),2),
  "se"=rep(c(.1,.1,.2,.05,.03),4))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM