我一直在努力为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
应为橙色等等......
答案 0 :(得分:1)
我建议创建一个与scale_fill_identity
一起使用的命名向量,而不是scale_fill_manual
。这样,您就不需要数据框中的颜色列。
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
行。