环境:Win 7 HP,R v2.15.1
我希望达到的目的:
- 绘制 y(数字)与 x(日期)
- 标签月-年缩写,按 mon+year 排序,las2 垂直对齐
- 按年份填充的颜色
- 按年分面网格
在阅读了这个论坛的不同主题后,我尝试了不同的方法,但无法得到我需要的东西。需要帮忙。附上样本数据和结果。
我的样本数据
x <- c("04-01-10","05-01-10","06-01-10","07-01-10","08-01-10","09-01-10","10-01-10","11-01-10","12-01-10","01-01-11","02-01-11","03-01-11","04-01-11","05-01-11","06-01-11","07-01-11","08-01-11","09-01-11","10-01-11","11-01-11","12-01-11","01-01-12","02-01-12","03-01-12","04-01-12","05-01-12","06-01-12")
y <- c(120,210,130,160,190,210,80,70,110,120,140,160,130,200,110,180,210,200,90,60,100,100,120,170,100,180,120)
x 是日期(字符),格式为 mm-dd-yy
转换为数据框
MySample <- data.frame(x) ## convert to dataframe
MySample$y <- y
加载所需的库
require(lubridate)
require(ggplot2)
MySample 基图
1) 绘制 x 与 y
ggplot(MySample, aes(MySample$x, MySample$y)) +
geom_bar(y=MySample$y,stat="identity")
给了我基本情节结果
2) 绘制 x 与 y + 填充 = 年
ggplot(MySample, aes(MySample$x, MySample$y, fill=year(MySample$x))) +
geom_bar(y=MySample$y,stat="identity")
给了我填充,但 2010,2010.5,2011,2011.5,2012 有 5 个填充年份
我尝试了不同的方法,但遇到了一个或另一个错误。
3) 绘制 x vs y + fill=year + facet_grid(year)
ggplot(MySample, aes(x, y, fill=year(x))) +
geom_bar(y=MySample$y,stat="identity") +
facet_grid(. ~ year(MySample$x))
获取:layout_base 中的错误(数据,cols,drop = drop):至少一层必须包含用于构面的所有变量
4) 绘制 x vs y + fill=year + facet_grid(year) + labels-month (abbr)
ggplot(MySample, aes(x, y, fill=year(x))) +
geom_bar(y=MySample$y,stat="identity") +
scale_x_date(labels=month(MySample$x,label=TRUE,abbr=TRUE))
获取:scale_labels.continuous(scale,major) 中的错误:中断和标签的长度不同
我被困住了,需要帮助才能继续前进。需要解决方案来满足以下要求:
- 仅 3 个填充年 - 2010、2011、2012
- xlabels - %b%y 格式;按月-年顺序排序;las2 定位(垂直)
- facet_grid 按年份,在适当的 facet-grid 中只有当年的 xlabels 和 bar