【问题标题】:ggplot and R: Two variables over timeggplot 和 R:随时间变化的两个变量
【发布时间】:2011-03-26 13:00:39
【问题描述】:

我想知道如何使 x 和 y,在下面的示例中,数据集在水平轴上框架的每个元素的垂直轴上绘制。如何使用 ggplot2 执行此操作?

x, y = 变量,帧 = YYYYMM

示例数据:

df <- structure(list(x = c(0.000892333625290767, 0.0161153931761482, 
0.0188150880795816, 0.0268699106638318, 0.018657330651898, 0.0101065034206662, 
0.00154410447630379), y = c(1.35172948829027, 0.59654026447333, 
0.685835030118683, 0.741545898152761, 1.09653338596292, 0.119448208345102, 
0.104092642854814), frame = c(200912, 201001, 201002, 201003, 
201004, 201005, 201006)), .Names = c("x", "y", "frame"), row.names = c("1", 
"2", "3", "4", "5", "6", "7"), class = "data.frame")

我已经能够将一个绘制成一条线,但它似乎没有将我的框架识别为分类(不是这样,我也不知道如何将其更改为此类)。

p <- ggplot(df, aes(x=frame, y=x))
p + geom_line()

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你需要融化你的数据:

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

    这就是你的数据框的作用:

    > 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
    

    【讨论】:

    • 谢谢,但这仍然将框架视为连续变量,而它应该是分类的
    • 熔炼前,将frame转成因子:df$frame = factor(df$frame)
    【解决方案2】:

    这是一个相当晚的答案,但是如果您想要 frame 变量解释日期(一年中的月份),请将其转换为日期。

    然后您可以使用 scale_x_datescales 包来格式化 x 轴

    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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 2020-03-09
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      相关资源
      最近更新 更多