Home > Mobile >  Connect the red points with a line in ggplot
Connect the red points with a line in ggplot

Time:12-02

Please help me; I made a plot comprising some red and blue points using ggplot. Now I want to connect the red points to each other with a line and connect the blue points to each other with another line These are my codes

m <- as.factor(c(7,"12 PCA", 21, "24 PCA", "31 PCA", 38, 70))
## Then we plot the points 
ggplot(pH, aes(x= m, y=All))  ylim(60,100) 
 scale_x_discrete(limits=c(7,"12 PCA", 21, "24 PCA", "31 PCA", 38, 70)) 
 geom_point(data=pH, aes(y=All), colour = 'red', size =1) 
 geom_point(data=pH, aes(y=Test), colour = 'blue', size=1)

And this is my plot This is my plot

How can I do that? Thanks

CodePudding user response:

I think it's generally best to not work with independent vectors of data when possible, instead placing it in a single frame. In this case, one column will be used to indicate which "group" the dots belong to.

dat <- data.frame(m=c(m,m), All=c(94,95,96,95,94,95,96, 74,67,74,67,68,73,74), grp=c(rep("red",7), rep("blue",7)))
dat
#         m All  grp
# 1       7  94  red
# 2  12 PCA  95  red
# 3      21  96  red
# 4  24 PCA  95  red
# 5  31 PCA  94  red
# 6      38  95  red
# 7      70  96  red
# 8       7  74 blue
# 9  12 PCA  67 blue
# 10     21  74 blue
# 11 24 PCA  67 blue
# 12 31 PCA  68 blue
# 13     38  73 blue
# 14     70  74 blue

Plot code:

library(ggplot2)
ggplot(dat, aes(m, All, group=grp, color=grp))   
  geom_point()   
  geom_line()   
  scale_color_manual(values = c(blue = "blue", red = "red"))

ggplot with colored/grouped lines

  • Related