如何通过ggplot geom_bar中的组填充

时间:2019-02-15 00:52:03

标签: r ggplot2 geom-bar

我正在尝试用显示组平均值的色标填充我的栏。输出仅显示一种阴影。

如何使每个条形的填充代表每年的CapacityFactor平均值。

最好采用ggplot方式,而不是对数据进行预处理。

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

metric004 <- data.frame(stringsAsFactors=FALSE,
            StationID = c("LOYYB", "LOYYB", "LOYYB", "LOYYB", "LOYYB", "LOYYB",
                          "LOYYB", "LOYYB", "OAKEY", "OAKEY", "OAKEY", "OAKEY",
                          "OAKEY", "OAKEY", "OAKEY", "OAKEY"),
                 DUID = c("LOYYB1", "LOYYB1", "LOYYB1", "LOYYB1", "LOYYB2",
                          "LOYYB2", "LOYYB2", "LOYYB2", "OAKEY1", "OAKEY1",
                          "OAKEY1", "OAKEY1", "OAKEY2", "OAKEY2", "OAKEY2",
                          "OAKEY2"),
           MonthStart = c(ymd("2017-11-01", "2017-12-01", "2018-01-01", "2018-02-01",
                          "2017-11-01", "2017-12-01", "2018-01-01",
                          "2018-02-01", "2017-11-01", "2017-12-01", "2018-01-01",
                          "2018-02-01", "2017-11-01", "2017-12-01", "2018-01-01",
                          "2018-02-01")),
       CapacityFactor = c(0.888504, 0.880521, 0.881841, 0.883836, 0.888695,
                          0.880279, 0.887361, 0.884969, 0, 0.027732, 0.007677,
                          0.038401, 0, 0.004178, 0.008861, 0.013907)
    )
m04_10y_faceted <- metric004 %>% group_by(StationID) %>%
    nest() %>%
    mutate(metricPlot = map(.x = data,
        ~ggplot(data=.x %>% group_by(year = as.Date(cut.Date(MonthStart, "year")))) +
            aes(year, CapacityFactor, fill = CapacityFactor) +
            stat_summary(fun.y = mean, na.rm = TRUE, geom = "bar") +
            scale_fill_continuous(limits=c(0,1)) +
            facet_grid(DUID ~ .) +
            xlab("Year") +
            ylab("Capacity Factor") +
            scale_x_date(date_breaks = "1 year", date_labels = "%Y", minor_breaks = NULL) +
            scale_y_continuous(limits=c(0, 1)) +
            coord_cartesian(xlim=c(ymd('2008-09-01'), ymd('2018-03-30'))) +
            theme_minimal() +
            theme(axis.title.x = element_blank(), axis.ticks = element_blank(),
                legend.position = "none")
    ))

walk2(m04_10y_faceted$StationID, m04_10y_faceted$metricPlot, function(.x, .y) {
    plot(.y)
})

from OP's link https://i.imgur.com/jevVETq.png

reprex package(v0.2.1)于2019-02-15创建

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的要求,则可以尝试:

  1. 更改fill参数:aes(year, CapacityFactor, fill = as.factor(year(MonthStart)))
  2. scale_fill_continuous()更改为scale_fill_manual(values = c("blue", "red"))

您可以在scale_fill_manual()中指定所需的任何颜色。