【问题标题】:Assigning colours to factor values in ggplot2 doesn't work将颜色分配给 ggplot2 中的因子值不起作用
【发布时间】:2018-01-08 17:53:13
【问题描述】:

我一直在努力为 ggplot2 中的值手动分配颜色。忽略字母顺序手动分配颜色的最简单方法是什么?

这是我的数据框,其中有一个 colours 列,表示每个 Status 所需的颜色:

    summary_count <– structure(list(Status = structure(c(4L, 6L, 1L, 5L, 2L, 3L), .Label = c("Compromise", 
"Launched", "Not yet rated", "Promise broken", "Promise kept", 
"Stuck"), class = "factor"), n = c(15L, 4L, 4L, 7L, 9L, 21L), 
    total = c(60, 60, 60, 60, 60, 60), colours = c("#B71C1C", 
    "#F57F17", "#2196F3", "#0D47A1", "#4CAF50", "#9E9E9E")), .Names = c("Status", 
"n", "total", "colours"), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

还有我的 ggplot 代码:

summary_count %>%
  ggplot(aes(x = Status, y = n, fill = Status)) +
  geom_col() +
  coord_flip() +
  geom_text(aes(label = n), 
            hjust = 1.5,
            colour = "white",
            fontface = "bold",
            size = 3) +
  scale_x_discrete(limits = rev(order)) +
  scale_fill_manual(values = summary_count$colours) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")

Promise broken 应该是红色,Stuck 应该是橙色等等...

【问题讨论】:

  • 感谢您使用dput,但似乎存在语法错误,可能缺少(。你能仔细检查一下吗?
  • 另外,要让@wibeasley 建议起作用,您需要在aes 调用中设置fill = colours
  • dput生成的数据框现在应该很好了。
  • 很好scale_identity 完全成功了!

标签: r ggplot2 colors


【解决方案1】:

我建议创建一个命名向量来与scale_fill_manual 一起使用,而不是scale_fill_identity。这样您就不需要数据框中的颜色列。

fill_colors = as.character(summary_count$colours)
names(fill_colors) = summary_count$Status

ggplot(summary_count, aes(x = Status, y = n, fill = Status)) +
  geom_col() +
  coord_flip() +
  geom_text(aes(label = n), 
            hjust = 1.5,
            colour = "white",
            fontface = "bold",
            size = 3) +
  #scale_x_discrete(limits = rev(order)) +
  scale_fill_manual(values = fill_colors) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.major.y = element_blank(),
        legend.position = "null")

我注释掉了 scale_x_discrete 行,因为您没有共享 order 变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2022-12-03
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多