【问题标题】:changing colour of bars in ggplot2 [closed]改变ggplot2中条形的颜色[关闭]
【发布时间】:2021-10-03 01:57:57
【问题描述】:

这是我的图表,我想给 4 个条形上色,一种颜色另一种颜色 4 个不同颜色,依此类推。如果我能加入一个传奇,那也很棒。

如何做到最好?

谢谢

【问题讨论】:

标签: r colors bar-chart


【解决方案1】:

一种选择是聚合数据并分配一个确定颜色的组。

plot_data <- tibble::tribble(
  ~label, ~value, ~group,
  "A",    1,      "Group 1",
  "B",    2,      "Group 1",
  "C",    3,      "Group 2"
)

library(ggplot2)

ggplot(plot_data) +
  aes(value, label, fill = group) +
  geom_col() +
  scale_fill_manual(values = c("steelblue", "darkred")) +
  theme_minimal()

【讨论】:

    【解决方案2】:

    您可以在aes 中添加fill

    示例数据:

    df <- data.frame(SFC = c("z","f",
                             "q",
                             "h",
                             "g",
                             "n" ,
                             "o",
                             "w"),
                     share = sample(1:100, 8)) %>% 
      arrange(share)
    
      SFC share
    1   q     4
    2   o    24
    3   h    25
    4   z    29
    5   f    44
    6   n    59
    7   g    72
    8   w    93
    

    代码:

    ordre <- df$SFC
    
    ggplot(df,aes(x = SFC,
                  y = share,
                  fill = factor(rep(seq(1:2), each=4)))) +
      geom_col() +
      scale_x_discrete(limits = ordre) +
      labs(fill = "Legend") +
      scale_fill_discrete(labels = c("first","second"))
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      相关资源
      最近更新 更多