ggplot:显示由特定变量

时间:2016-05-26 09:29:06

标签: r ggplot2

这是一个简单的问题,但我试图在ggplot中制作一个图表,并且我很难根据变量' time'成功地显示数据。我的数据如下:

id  season       sex    treatment   time    shift(Km)
1   Early dry   PRIDES  UNDISTURBED BEFORE  0.016
2   Early dry   PRIDES  UNDISTURBED BEFORE  0.016
3   Early dry   PRIDES  UNDISTURBED BEFORE  0.016
4   Wet         PRIDES  DISTURBED   AFTER   0.0972

我希望最终的图形具有如下图所示的精确布局,但我还没想到的是如何根据变量' time'成对绘制我的响应变量,是,显示每个'处理的配对前后值。组(受干扰/未受干扰),不在彼此之上,如下图所示。

enter image description here

这是我的代码:

ex <- read.csv(file = "https://dl.dropboxusercontent.com/u/23723553/data.csv",
               header= TRUE, row.names =1)

ex$time <- relevel(ex$time, ref = "BEFORE")

ggplot(data = ex, mapping = aes(x = treatment,
                                        y = dist_shift.Km., 
                                        shape= time)) +
  stat_summary(fun.data = mean_se) +
  facet_grid(season ~ sex)+
  labs(x= "\nTreatment", y = "Shift of centroids (m)\n")+
  theme_bw()

有人可以帮我修改我的代码吗?

更新:根据@lukeA的建议绘制时间/治疗互动,让我更接近我的目标,但是在交互之前勾画出相互影响的情节&#39;在&#39;之前不受干扰然后在&#39;之后感到不安&#39;在&#39;之后不受干扰。我想并排绘图:&#39;扰乱之前&#39; &#39;在&#39;之后受到干扰,并且在&#39;之前不受干扰?在&#39;之后不受干扰。

enter image description here

而且,有没有办法改变x轴上的名字,所以我只能打扰&#39; &#39;不受干扰&#39;而不是&#39; disturbed.before&#39;之前/之后的时间已经由形状解释并在图例中描述。

非常感谢!

2 个答案:

答案 0 :(得分:1)

你可以做例如

ggplot(data = ex, mapping = aes(x = interaction(time, treatment),
                                        y = dist_shift.Km., 
                                        shape= time)) +
  stat_summary(fun.data = mean_se) +
  facet_grid(season ~ sex)+
  labs(x= "\nTreatment", y = "Shift of centroids (m)\n")+
  scale_x_discrete(labels = function(x) sub(".*\\.", "", x)) +
  theme_bw() + 
  theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1))

enter image description here

答案 1 :(得分:1)

您只需要将position=position_dodge()参数添加到stat_summary(),以便在值彼此接近之前和之后放置。

ggplot(data = ex, mapping = aes(x = treatment,
                                y = dist_shift.Km., 
                                shape= time)) +
      stat_summary(fun.data = mean_se,position = position_dodge(width=0.2)) +
      facet_grid(season ~ sex)+
      labs(x= "\nTreatment", y = "Shift of centroids (m)\n")+
      theme_bw()

enter image description here