使用 ggplot 绘制多列 df

Plotting multiple columns of df using ggplot

这个问题与 r - data frame of lists into a data frame 类似,但没有真正足够的答案。

我有一个 df 的时间序列数据,将模型数据与量具数据进行比较。请参阅下面的数据子部分:

Date        GageFlow  base0      1a       1b       2a        2b       3a       
2003-10-01     78.6 72.43154 64.55318 64.55318 64.55318 64.55318 64.55318 
2003-10-02     88.6 74.94789 68.48789 68.48789 68.48789 68.48789 68.48789 
2003-10-03     96.6 75.08756 69.75530 69.75530 69.75530 69.75530 69.75530 
2003-10-04     93.1 74.45323 66.67482 66.67482 66.67482 66.67482 66.67482 
2003-10-05     90.2 72.89045 65.24120 65.24120 65.24120 65.24120 65.24120 
2003-10-06     96.0 73.89078 67.88296 67.88296 67.88296 67.88296 67.88296 

我的数据str是:

'data.frame':   3653 obs. of  11 variables:
 $ Date    : Date, format: "2003-10-01" "2003-10-02" ...
 $ GageFlow: num  78.6 88.6 96.6 93.1 90.2 96 96 97.8 98.7 99.8 ...
 $ base0   :'data.frame':   3653 obs. of  1 variable:
  ..$ base0: num  72.4 74.9 75.1 74.5 72.9 ...

我想使用 ggplot 绘制模型场景图,其中 geom_lines of (base0, 1a, 1b, 等等.) 和 GageFlow,其中 x-axis 作为 timeseries (x=Date) 提供。问题是,当我使用 melt 尝试以高格式获取它时,我收到错误消息:

Error: Can't melt data.frames with non-atomic 'measure' columns In addition: Warning message: attributes are not identical across measure variables; they will be dropped

我真的需要重组我的 df 还是有什么方法可以 melt,或者使用其他函数来生成这样的图。当然我可以做很长的路要走,但我正在努力变得更有效率。

谢谢!

要解决这个问题,你必须转换base0变量。

str(df)
## 'data.frame':    6 obs. of  8 variables:
##  $ Date    : Date, format: "2003-10-01" ...
##  $ GageFlow: num  78.6 88.6 96.6 93.1 90.2 96
##  $ base0   :'data.frame':    6 obs. of  1 variable:
##   ..$ df$base0: num  72.4 74.9 75.1 74.5 72.9 ...

# Alternatively, you can use df$base0 <- df$base0[, 1]
# if you only have few columns which classes are data.frame
df[] <- lapply(df, unlist)

str(df)
## 'data.frame':    6 obs. of  8 variables:
##  $ Date    : Date, format: "2003-10-01" ...
##  $ GageFlow: num  78.6 88.6 96.6 93.1 90.2 96
##  $ base0   : num  72.4 74.9 75.1 74.5 72.9 ...

df <- melt(df, "Date")
ggplot(df, aes(x=Date, y=value, color=variable)) + geom_line()