首页 > 解决方案 > ggplot2和一组抖动/闪避点

问题描述

我将“海拔”作为我的 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 轴(我想不出一种方法来保持这一点,但不能用离散的比例显示所有刻度线)。

谢谢您的帮助。

标签: rggplot2

解决方案


如果要将数值用作离散值,则应使用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 提供的示例数据进行编辑

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

然后,我没有通过您facotr(...)在问题中提供的 commdnas,而是使用as.factor(Elevation)andposition_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))

推荐阅读