r - 如何根据x轴改变折线图的颜色?
问题描述
我有以下数据框
structure(list(dteday = c("2011-01", "2011-02", "2011-03", "2011-04",
"2011-05", "2011-06", "2011-07", "2011-08", "2011-09", "2011-10",
"2011-11", "2011-12", "2012-01", "2012-02", "2012-03", "2012-04",
"2012-05", "2012-06", "2012-07", "2012-08", "2012-09", "2012-10",
"2012-11", "2012-12"), cnt = c(38189L, 48215L, 63422L, 94870L,
135821L, 143512L, 141341L, 136691L, 127418L, 123511L, 102167L,
87323L, 96744L, 103137L, 164875L, 174224L, 195865L, 202830L,
203607L, 214503L, 218573L, 198841L, 152664L, 123713L)), row.names = c(NA,
-24L), class = c("tbl_df", "tbl", "data.frame"))
这是我当前的折线图
ggplot(bike2, aes(x=dteday, y=cnt, group = 1))+
geom_line(color = "green", size = 1.2) +
labs(title = "Bike Rentals Per Month",
x = "Month/Year",
y = "Count") +
theme_solarized() +
theme(axis.text.x=element_text(angle=45, hjust=1))
x 轴是根据月份和年份。我想要的是 2011 年为黄色,然后 2012 年为绿色,以更好地区分年份。
解决方案
从数据中提取年份数据并将其用作color
.aes
library(ggplot2)
ggplot(transform(bike2, year = substr(dteday, 1, 4)),
aes(x=dteday, y=cnt, group = 1, color = year))+
geom_line(size = 1.2) +
labs(title = "Bike Rentals Per Month",
x = "Month/Year",
y = "Count") +
#theme_solarized() +
theme(axis.text.x=element_text(angle=45, hjust=1))
如果你想给年份一些特定的颜色,你可以通过+ scale_color_manual(values = c('green', 'yellow'))
.
推荐阅读
- ray - 我可以强制任务/演员在特定节点上运行吗?使用雷
- javascript - 为什么我们可以在动画手风琴中使用 height 属性而不是 max-height 属性?
- android - 如何从 FirebaseApp.initializeApp() 的“辅助”应用程序获取令牌
- r - 当全局模型有优化器时从 Dredge() 获取 R^2
- swift - 快速设置单元格委托会出错
- ksqldb - 运行某些查询时重新启动 KSQL-Server
- angular - 在更新和验证子组件后运行 ControlValueAccessor validate
- clickhouse - ClickHouse ,选择 top n 并按主键排序的问题
- c - 浅层和深层析构函数?
- android - 固定 TabLayout 中每页的选项卡数