Reputation: 189
This is a simple question, but I am trying to make a graph in ggplot and I am having a hard time trying to show the data in pairs according to the variable 'time'. My data looks like this:
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
I would like the final graph to have the exact layout as the graph below, but what I have not figure out yet is how to plot my response variable in pairs according to the variable 'time', that is, to show the before and after values paired for each 'treatment' group (disturbed/undisturbed), not on top of each other as it is showing in the graph below.
This is the code I have:
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()
Could someone help me modify my code?
UPDATE: plotting the time/treatment interaction as suggested by @lukeA gets me closer to what I am aiming for, but graphing the interaction plots side by side 'disturbed before' with 'undisturbed before' and then 'disturbed after' with 'undisturbed after'. I would like to plot instead side by side: 'disturbed before' with 'disturbed after', and 'undisturbed before' with 'undisturbed after'.
And, is there a way to change the names in the x axis so I can have only 'disturbed' 'undisturbed' instead of 'disturbed.before' etc. The time before/after is already explained by the shape and described in the legend.
Many thanks!
Upvotes: 2
Views: 385
Reputation: 98489
You just have to add argument position=position_dodge()
to stat_summary()
to place before and after values close to each other.
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()
Upvotes: 1
Reputation: 54237
You could for example do
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))
Upvotes: 1