2.6 绘制面积图
运行 geom_area() 函数即可绘制面积图
# 将sunspot.year数据集转化为数据框,便于本例使用 sunspotyear <- data.frame(Year = as.numeric(time(sunspot.year)), Sunspots = as.numeric(sunspot.year))ggplot(sunspotyear, aes(x = Year, y = Sunspots)) + geom_area()
# 颜色、透明度设置 ggplot(sunspotyear, aes(x = Year, y = Sunspots)) + geom_area(colour = "black",fill = "blue", alpha = 0.2)
# 去掉底部横线 不设定colour,使用geom_line()绘制轨迹 ggplot(sunspotyear, aes(x = Year, y = Sunspots)) + geom_area(fill = "blue",alpha = 0.2) + geom_line()
2.7 绘制堆积面积图
library(gcookbook) ggplot(uspopage, aes(x = Year, y = Thousands, fill = AgeGroup)) + geom_area()
head(uspopage)
> head(uspopage) Year AgeGroup Thousands 1 1900 <5 9181 2 1900 5-14 16966 3 1900 15-24 14951 4 1900 25-34 12161 5 1900 35-44 9273 6 1900 45-54 6437
# 通过设定breaks翻转堆积顺序 # 透明度、颜色、大小设置 ggplot(uspopage, aes(x = Year, y = Thousands, fill = AgeGroup)) + geom_area(colour = "black", size = 0.2, alpha = 0.4) + scale_fill_brewer(palette = "Blues", breaks = rev(levels(uspopage$AgeGroup)))
# 设定order = desc(AgeGroup) 可以对堆积顺序进行反转 library(plyr) ggplot(uspopage, aes(x = Year, y = Thousands, fill = AgeGroup, order = desc(AgeGroup))) + geom_area(colour = "black", size = 0.2, alpha = 0.4) + scale_fill_brewer(palette = "Blues")
# 去掉框线 ggplot(uspopage, aes(x = Year, y = Thousands, fill = AgeGroup, order = desc(AgeGroup))) + geom_area(colour = NA, alpha = 0.4) + scale_fill_brewer(palette = "Blues") + geom_line(position = "stack", size = 0.2)
2.8 绘制百分比面积堆积图
# 先计算百分比 uspopage_prop <- ddply(uspopage, "Year", transform, Percent = Thousands/sum(Thousands) * 100) ggplot(uspopage_prop, aes(x = Year, y = Percent, fill = AgeGroup)) + geom_area(colour = "black", size = 0.2, alpha = 0.4) + scale_fill_brewer(palette = "Blues", breaks = rev(levels(uspopage$AgeGroup)))
网络异常,图片无法展示
|
head(uspopage)
> head(uspopage) Year AgeGroup Thousands 1 1900 <5 9181 2 1900 5-14 16966 3 1900 15-24 14951 4 1900 25-34 12161 5 1900 35-44 9273 6 1900 45-54 6437
uspopage_prop <- ddply(uspopage, "Year", transform, Percent = Thousands/sum(Thousands) * 100)
2.9 添加置信域
运行 geom_ribbon()分别映射一个变量给 ymin 和 ymax。
climate数据集中的Anomaly10y变量表示了各年温度相对于1950-1980平均水平变异的10年移动平均。Unc10y表示其95%置信区间。
library(gcookbook) # 抓取 climate 数据的一个子集 clim <- subset(climate, Source == "Berkeley", select = c("Year", "Anomaly10y", "Unc10y")) head(clim)
> head(clim) Year Anomaly10y Unc10y 1 1800 -0.435 0.505 2 1801 -0.453 0.493 3 1802 -0.460 0.486 4 1803 -0.493 0.489 5 1804 -0.536 0.483 6 1805 -0.541 0.475
# 将置信域绘制为阴影 # 注意一下图层的顺序 ggplot(clim, aes(x = Year, y = Anomaly10y)) + geom_ribbon(aes(ymin = Anomaly10y - Unc10y, ymax = Anomaly10y + Unc10y), alpha = 0.2) + geom_line()
# 使用虚线表示置信域的上下边界 ggplot(clim, aes(x = Year, y = Anomaly10y)) + geom_line(aes(y = Anomaly10y -Unc10y), colour = "grey50", linetype = "dotted") + geom_line(aes(y = Anomaly10y +Unc10y), colour = "grey50", linetype = "dotted") + geom_line()
参考书籍
R Graphics Cookbook, 2nd edition.