【问题标题】:Conditionally Colouring Bars in Ggplot2Ggplot2中的有条件着色条
【发布时间】:2016-04-14 02:53:36
【问题描述】:

下面是一些简单示例数据框和绘图的代码。我想知道如何有条件地为条形着色。我熟悉 scale_fill_manual 来手动给条形上色,但是如果我希望 2016 构面中的 "Satisfied" 比 2015 中的 "Satisfied" 的百分比低,那该怎么办。可能是红色警告边框或其他颜色,如橙色(仅作为示例)。

这不是最好的例子,但如果我有一个年度顶盒得分图,如果条形图下降到某个百分比以下,这将有助于使条形图改变颜色。我尝试使用"colour = ifelse(Perc < 60, "orange", "green" 组合,但无法使其正常工作。我不确定如何构造 ifelse 语句或将其放置在 ggplot 代码中的什么位置。

Year<-c(2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016)

Service<-c("Satisfied", "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied",
           "Satisfied", "Satisfied", "Dissatisfied", "Dissatisfied", "Dissatisfied")

df <- data.frame(Year, Service)

library(dplyr)
df.prop <- df %>%
            count(Year, Service) %>%
            mutate(Perc = prop.table(n))

library(ggplot2)
ggplot(df.prop, aes(x = Service, y = Perc, fill = Service)) +
       geom_bar(stat = "identity", position = "dodge") +
       geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
                 vjust = 1.5, size = 3) +
       scale_y_continuous(labels = percent) +
       facet_grid( ~ Year)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    向数据框添加新变量可能是最简单的方法:

    df.prop$colour <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", NA)
    

    那么你可以这样做:

    ggplot(df.prop, aes(x = Service, y = Perc, fill = Service, colour=colour)) +
      geom_bar(stat = "identity", position = "dodge") +
      geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
                vjust = 1.5, size = 3, colour="black") +
      scale_y_continuous(labels = percent) +
      facet_grid( ~ Year) +
      scale_colour_identity()
    

    如果您想根据条件更改填充,您可以这样做:

    df.prop$fill <- ifelse(df.prop$Service == "Satisfied" & df.prop$Perc < 0.6, "orange", ifelse(df.prop$Service == "Satisfied" & df.prop$Perc >= 0.6, "#00BFC4", "#F8766D"))
    
    ggplot(df.prop, aes(x = Service, y = Perc, fill = fill)) +
      geom_bar(stat = "identity", position = "dodge") +
      geom_text(aes(label = percent(Perc)), position = position_dodge(width = 1),
                vjust = 1.5, size = 3) +
      scale_y_continuous(labels = percent) +
      facet_grid( ~ Year) +
      scale_fill_identity()
    

    【讨论】:

    • 感谢您的回答,效果很好。只是一个后续问题,答案允许我添加彩色边框,但我如何将实际的条形颜色更改为橙​​色而不仅仅是轮廓?
    • 如何获得第二张图的图例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多