简体   繁体   中英

How to plot two lines on one plot with ggplot2 while specifying order of the x-axis labels?

The data are in "stats":

run       valence mean sd sem
Nnf1_mINS   n     2.1 .5 .01
Nnf2_mINS   p     3.2 .2 .01
Nobs_mINS   n     2.3 .1 .02

Here's my code:

ggplot(stats,aes(x=run,y=mean,color=valence,group=1))+ 
    geom_point() +
    geom_line()+
    geom_errorbar(aes(ymin = mean - sem, ymax = mean + sem),                         
                  width = 0.2,
                  position = position_dodge(0.9))

3 problems:

  1. to specify the order on x axis, I turned the variable into a factor:
stats$run <- factor(stats$run, levels = c("Nobs_mINS","Nnf1_mINS","Nnf2_mINS"))
  1. but to plot 2 lines on one plot, there can't be a factor variable. This is the error: "geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?" I fixed this error by adding "group=1" thanks to this post: ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

  2. For some reason the line is not connected correctly: 在此处输入图像描述

Well, group = valence solves the problem! Here's the edited code:

ggplot(stats,aes(x=run,y=mean,color=valence,group=valence))+ 
    geom_point() +
    geom_line()+
    geom_errorbar(aes(ymin = mean - sem, ymax = mean + sem),                         
                  width = .2,
                  position = position_dodge(.09))+
    theme(text = element_text(size=15),
          axis.text.x = element_text(angle=0, hjust=1))+
    scale_y_continuous(limits = c(-0.22, 0.1))

the graph: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM