Grouping by coefficient with sloped position in ggplot

Let's look at some dummy data. I have various combinations of items, treatments, and challenges. In fact, each subject is only associated with a specific treatment (sounds silly, but this is just an example).

library(ggplot2)
d = read.table(text = '
subject   treatment trial     value
1    1    1    4.5
2    2    1    3.2
3    3    1    1.2
1    1    2    4.8
2    2    2    3.5
3    3    2    1.3
1    1    3    4.2
2    2    3    2.9
3    3    3    1
4    1    1    4.3
5    2    1    3.9
6    3    1    1.1
4    1    2    4.3
5    2    2    3.1
6    3    2    1.8
4    1    3    4
5    2    3    2.6
6    3    3    1.3
', header = TRUE)
d$treatment = as.factor(d$treatment)
d$subject = as.factor(d$subject)
d$trial = as.factor(d$trial)

dodge = position_dodge(.3)
p = ggplot(d, aes(x = treatment, y = value, color = trial, label = subject)) + 
  geom_point(position = dodge) +
  scale_y_continuous(breaks = pretty_breaks(n = 10)) +
  ylim(1,5) +
  geom_text(hjust = 1.5, position = dodge, size = 3)

print(p)

      

The plot I get is this:

I would like to add a line between the same topics, which means that I would like to concatenate all "4" in the upper left corner with a black line.

Plain

geom_line(aes(group = subject), position = dodge)

      

doesn't work, although it somehow doesn't respect the position and just draws a vertical line:

How else can I achieve this?

+3


source to share


1 answer


I think you need to rethink your approach - dodging doesn't work well with lines. Why not use a facet and explicitly display the trial on the x-axis?

ggplot(d, aes(trial, y = value)) + 
  geom_line(aes(group = subject)) +
  geom_point(aes(colour = treatment)) +
  geom_text(aes(label = subject), hjust = 1.5, size = 3)  +
  facet_wrap(~ treatment)

      



.....

+5


source







All Articles