Plot two graphs in same plot in R

前端 未结 16 1048
感情败类
感情败类 2020-11-22 03:37

I would like to plot y1 and y2 in the same plot.

x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = \"l\", col = \"red\")         


        
16条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 03:54

    As described by @redmode, you may plot the two lines in the same graphical device using ggplot. In that answer the data were in a 'wide' format. However, when using ggplot it is generally most convenient to keep the data in a data frame in a 'long' format. Then, by using different 'grouping variables' in the aesthetics arguments, properties of the line, such as linetype or colour, will vary according to the grouping variable, and corresponding legends will appear.

    In this case, we can use the colour aessthetics, which matches colour of the lines to different levels of a variable in the data set (here: y1 vs y2). But first we need to melt the data from wide to long format, using e.g. the function 'melt' from reshape2 package. Other methods to reshape the data are described here: Reshaping data.frame from wide to long format.

    library(ggplot2)
    library(reshape2)
    
    # original data in a 'wide' format
    x  <- seq(-2, 2, 0.05)
    y1 <- pnorm(x)
    y2 <- pnorm(x, 1, 1)
    df <- data.frame(x, y1, y2)
    
    # melt the data to a long format
    df2 <- melt(data = df, id.vars = "x")
    
    # plot, using the aesthetics argument 'colour'
    ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line()
    

    enter image description here

提交回复
热议问题