r - 如何制作一个遵循时间序列但对来自不同因素的条形图使用不同颜色的条形图
问题描述
我希望这个标题不会太混乱。我有 10 个日期的数据,每个数据点都标记为“灌溉”或“降水”。我想制作一个条形图,其中每个值按时间顺序都有一个条形图,条形图下方标有日期,但也希望对条形图进行颜色编码(例如,“灌溉”中的所有条形图都是红色的,而来自“降水”的那些将是蓝色的。)
我对R相当陌生,这可能吗?如果是这样,任何帮助将不胜感激。
这是我的数据:
dput(head(data))
structure(list(Date = structure(4:9, .Label = c("7/11/2019",
"7/13/2019", "7/15/2019", "7/2/2019", "7/3/2019", "7/4/2019",
"7/5/2019", "7/6/2019", "7/7/2019", "7/9/2019"), class = "factor"),
Inches = c(1.6, 0.02, 0.35, 0.64, 0.07, 0.35), Type = structure(c(2L,
2L, 1L, 2L, 2L, 1L), .Label = c("Irrigation", "Precipitation"
), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
解决方案
您可以使用dplyr
和ggplot2
制作条形图。该stat='identity'
调用意味着每个条形高度使用数据中的相应值,并将position='dodge'
条形并排放置,而不是堆叠。
df <- data.frame(date=c(paste0('2019-0',1:9),'2019-10'),
precipitation=runif(10),irrigation=runif(10))
df
df %>% gather(k,v,-date) %>%
ggplot(aes(date,v,fill=k)) + geom_bar(stat='identity',position = 'dodge') +
theme(axis.text.x = element_text(angle = 45,hjust=1))
编辑
这是使用您提供的数据的条形图dput
。我没有意识到您的数据已经分组在一列中。
df <- structure(list(Date = structure(4:9, .Label = c("7/11/2019",
"7/13/2019", "7/15/2019", "7/2/2019", "7/3/2019", "7/4/2019",
"7/5/2019", "7/6/2019", "7/7/2019", "7/9/2019"), class = "factor"),
Inches = c(1.6, 0.02, 0.35, 0.64, 0.07, 0.35), Type = structure(c(2L,
2L, 1L, 2L, 2L, 1L), .Label = c("Irrigation", "Precipitation"
), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
df %>% ggplot(aes(Date,Inches,fill=Type)) + geom_bar(stat='identity',position = 'dodge') +
theme(axis.text.x = element_text(angle = 45,hjust=1))
推荐阅读
- java - 是否可以让 JUnit5 Extension 实现由扩展类实现的接口?
- lua - Lua 中逗号分隔的 return 语句如何充当函数调用?
- android - 启动服务时是否保证启动 react javascript 运行时?
- google-app-maker - GSuite Appmaker - 如何使用按钮在表格中设置默认值
- arrays - SAS:在列中的最后一个条目后添加值
- c# - 可以在 PHP 中运行的 C# 程序中运行命令吗?
- python - 如何在字符串中搜索后跟特定单词的任何数字?
- azure - 在 Microsoft Azure 中,Azure AD 设备和 MSOL 设备有什么区别
- python - 如何使用 numpy 从二进制文件中获取字节数据
- c++ - 所有变量是否都根据它们在程序中声明的顺序连续存储?