Using both geom_point and geom_line for multiple X

2019-09-01 08:56发布

问题:

So I have a data.frame:

Plan  Person X       mm  mean_mm
1  1 95 0.323000 0.400303
1  2 275 0.341818 0.400303
1  3  2 0.618000 0.400303
1  4 75 0.320000 0.400303
1  5 13 0.399000 0.400303
1  6 20 0.400000 0.400303
2  1 219 0.393000 0.353350
2  2 50 0.060000 0.353350
2  3 213 0.390000 0.353350
2  4 204 0.496100 0.353350
2  5 19 0.393000 0.353350
2  6 201 0.388000 0.353350

etc to Plan == 40

I want to use ggplot2 to plot points mm (colored by X) but have a plot a line for mm_mean from person 1 to person 6 in each Plan. I've used the code to plot mm (sorted by plan):

mc.points <- ggplot(sam,aes(x = person,y = mm, colour = X, size = 3)) +
geom_point() +
labs(x = "Plan/Person",y = "mm") +
scale_colour_gradient2(high="red", mid="green", limits=c(0,1), guide = "colourbar") 

Which is successful. But not sure if adding geom_line() to plot the mm_mean line will be enough given I haven't specified mm_mean in the above code (although it can be plotted against the y axis given its the mean of this). And if so, how can this be done? And will this work if I want to keep adding variables on top of this which are not related to mm or mm_mean?

I can provide more info if needed

回答1:

Something like this?

ggplot(df, aes(x = Person,y = mm, colour = X)) +
  geom_point(size = 3) +
  geom_hline(aes(yintercept = mean_mm)) +
  facet_wrap(~ Plan)



回答2:

to change the layout of the faceted plots,

facet_wrap(~ Plan, ncol = 4) # or however many columns you want so that the layout looks appealing.



标签: r plot ggplot2