绘制数据框但不知道如何提取变量

时间:2015-11-30 01:03:44

标签: r ggplot2

我有一个像这样的数据框:

            1999      2002      2005      2008

POINT    1323759.8  883223.8  963392.9  734288.6

NONPOINT 5518185.3 4254247.0 4043390.2 2438866.9

ON-ROAD   183895.1  154222.2  134291.8  107384.1

NON-ROAD  307126.5  344087.5  313628.1  183666.2

我想分别针对四种类型“POINT”“NONPOINT”“ON-ROAD”“NON-ROAD”制作年度排放变化图。但我不知道如何引用变量。也许这种格式是我想要的。

qplot(year,emission,data=df,facets = type~.)

1 个答案:

答案 0 :(得分:4)

我认为你想使用melt

#Recreate input data 
sample_input = data.frame(
   type = c("POINT", "NONPOINT", "ON-ROAD", "NON-ROAD"),
   A = rnorm(4, 1e4),
   B = rnorm(4, 1e4),
   C = rnorm(4, 1e4),
   D = rnorm(4, 1e4)
 )

 colnames(sample_input) = c("type", "1999", "2002", "2005", "2008")

 df = reshape2::melt(sample_input, measure.vars = c("1999", "2002", "2005", "2008"),
                       variable.name = "year", value.name = "emission")

 library(ggplot2)

 qplot(year,emission,data=df,facets = type~.)