使用R中的qplot绘制汇总数据

时间:2014-05-17 12:51:30

标签: r ggplot2

我想使用bal方面对qplot进行交叉分类和绘制:

> str(bal)
'data.frame':   2096 obs. of  6 variables:
 $ fips     : chr  "24510" "24510" "24510" "24510" ...
 $ SCC      : chr  "10100601" "10200601" "10200602" "30100699" ...
 $ Pollutant: chr  "PM25-PRI" "PM25-PRI" "PM25-PRI" "PM25-PRI" ...
 $ Emissions: num  6.53 78.88 0.92 10.38 10.86 ...
 $ type     : chr  "POINT" "POINT" "POINT" "POINT" ...
 $ year     : int  1999 1999 1999 1999 1999 1999 1999 1999 1999 1999 ...

我对两个分类器yeartype感兴趣:

> levels(factor(bal$year))
[1] "1999" "2002" "2005" "2008"
> levels(factor(bal$type))
[1] "NON-ROAD" "NONPOINT" "ON-ROAD"  "POINT"   

我到目前为止,我可以绘制Emissions按年份和类型进行交叉分类的分布情况: enter image description here 我无法做的是绘制每年分布的sum,但我能够计算出来:

> tapply(bal$Emissions, list(bal$year, bal$type), sum)
      NON-ROAD NONPOINT   ON-ROAD     POINT
1999 522.94000 2107.625 346.82000  296.7950
2002 240.84692 1509.500 134.30882  569.2600
2005 248.93369 1509.500 130.43038 1202.4900
2008  55.82356 1373.207  88.27546  344.9752

我的猜测是

> qplot(bal$year, tapply(bal$Emissions, list(bal$year, bal$type), sum), 
        data=bal, facets= . ~ type)
Error: Aesthetics must either be length one, or the same length as the
dataProblems:tapply(bal$Emissions, list(bal$year, bal$type), sum)

但我得不到R在那里告诉我的内容。

如何使用qplot绘制此矩阵?

1 个答案:

答案 0 :(得分:2)

你可以使用ggplot

来做到这一点
qplot(year, Emissions, data=bal, 
    stat="summary", fun.y="sum",
    facets= .~type
)

ggplot(bal) +
    aes(year, Emissions) +
    stat_summary(fun.y="sum",geom="point") + 
    facet_grid(.~type)

两者都应该为您提供以下图表,该图表似乎与您的汇总数据完全匹配。

plot with summarized data