【问题标题】:How to fill by mean of a group in ggplot geom_bar如何通过ggplot geom_bar中的组填充
【发布时间】:2019-07-09 02:54:24
【问题描述】:

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

我怎样才能使这项工作让每个条形的填充代表每年的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)
})

reprex package (v0.2.1) 于 2019 年 2 月 15 日创建

【问题讨论】:

  • 添加了源数据的选择。董 - 感谢您的提示。

标签: r ggplot2 geom-bar


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 2019-08-19
    • 2015-10-19
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多