ggplot and R: Two variables over time

后端 未结 2 2000
清酒与你
清酒与你 2020-12-06 11:32

I\'d like to know how to make it so that x and y, in the following example data set are plotted on the vertical axis for each element of frame in the horizontal axis. How do

相关标签:
2条回答
  • 2020-12-06 12:16

    This is a rather late answer, but if you want your frame variable intepreted date (month of the year), then convert it to a date.

    You can then use scale_x_date and the scales package to format the x-axis

    DF <- melt(df, id.vars = 'frame')
    # note that I am arbitrarily setting each month to be the 15th 
    # day of the month, to create a complete date 
    DF$date <- as.Date(paste0(as.character(df$frame), '15'), '%Y%M%d')
    library(scales)
    ggplot(DF, aes(x =frame, y = value, colour = variable))  +  
     geom_line() + 
     scale_x_date('Month', labels = date_format('%b %Y'), breaks = date_breaks('2 months'))
    

    enter image description here

    0 讨论(0)
  • 2020-12-06 12:18

    You need to melt your data:

    library(reshape2)
    dfm = melt(df, id.vars='frame')
    ggplot(dfm, aes(x=frame, y=value, colour=variable)) + geom_line()
    

    This is what that does to your data frame:

    > dfm
        frame variable        value
    1  200912        x 0.0008923336
    2  201001        x 0.0161153932
    3  201002        x 0.0188150881
    4  201003        x 0.0268699107
    5  201004        x 0.0186573307
    6  201005        x 0.0101065034
    7  201006        x 0.0015441045
    8  200912        y 1.3517294883
    9  201001        y 0.5965402645
    10 201002        y 0.6858350301
    11 201003        y 0.7415458982
    12 201004        y 1.0965333860
    13 201005        y 0.1194482083
    14 201006        y 0.1040926429
    
    0 讨论(0)
提交回复
热议问题