首页 > 解决方案 > 如何制作一个遵循时间序列但对来自不同因素的条形图使用不同颜色的条形图

问题描述

我希望这个标题不会太混乱。我有 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")

标签: r

解决方案


您可以使用dplyrggplot2制作条形图。该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))

条形图 2


推荐阅读