如何根据条件向ggplot添加2种以上的颜色?
How to add more than 2 colours to ggplot based on conditions?
我的问题有点像这里回答的问题:
但是,虽然我希望所有的负值都是相同的颜色(例如深蓝色),但我希望每年的正值都具有不同的颜色。然而,当我制作一个颜色矢量(如下图)时,我最终得到的每个条都是矢量中所有颜色的混合。
vector <- ('2005'='pink', '2010'='green', '2011'='yellow')
我想为每个正数年份设置不同的颜色,同时让所有负数年份都只有一种颜色。
您可以从 post you referenced 扩展相同的想法。本质上,您可以创建一个指定正值和负值之间的新变量;但是,我们可以使用年份而不是使用“积极”。然后,我们仍然可以使用 scale_fill_manual
来设置颜色。因此,所有负值都将是一种颜色。然后,对于每个正值,我们可以给一个唯一的颜色。
library(tidyverse)
df %>%
mutate(grp = ifelse(value >= 0, as.character(variable), "negative")) %>%
ggplot(aes(x = variable, y = value, fill = grp)) +
geom_col() +
scale_fill_manual(values = c("negative" = "darkblue", "2002" = "blue", "2003" = "red",
"2004" = "orange", "2005" = "yellow", "2007" = "darkred",
"2008" = "purple", "2009" = "green", "2012" = "darkgreen"))
输出
数据
df <- structure(list(Mealtime = c("Breakfast", "Breakfast", "Breakfast", "Breakfast",
"Breakfast", "Breakfast", "Breakfast", "Breakfast",
"Breakfast", "Breakfast", "Breakfast"),
Food = c("Rashers", "Rashers", "Rashers", "Rashers", "Rashers",
"Rashers", "Rashers", "Rashers", "Rashers", "Rashers", "Rashers"),
variable = structure(1:11, .Label = c("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010",
"2011", "2012"), class = "factor"),
value = c(9.12, 9.5, 2.04, -20.72, 18.37, 91.19, 94.83,
191.96,-125.3,-18.56, 63.85)),
row.names = c(NA, -11L), class = "data.frame")
我的问题有点像这里回答的问题:
但是,虽然我希望所有的负值都是相同的颜色(例如深蓝色),但我希望每年的正值都具有不同的颜色。然而,当我制作一个颜色矢量(如下图)时,我最终得到的每个条都是矢量中所有颜色的混合。
vector <- ('2005'='pink', '2010'='green', '2011'='yellow')
我想为每个正数年份设置不同的颜色,同时让所有负数年份都只有一种颜色。
您可以从 post you referenced 扩展相同的想法。本质上,您可以创建一个指定正值和负值之间的新变量;但是,我们可以使用年份而不是使用“积极”。然后,我们仍然可以使用 scale_fill_manual
来设置颜色。因此,所有负值都将是一种颜色。然后,对于每个正值,我们可以给一个唯一的颜色。
library(tidyverse)
df %>%
mutate(grp = ifelse(value >= 0, as.character(variable), "negative")) %>%
ggplot(aes(x = variable, y = value, fill = grp)) +
geom_col() +
scale_fill_manual(values = c("negative" = "darkblue", "2002" = "blue", "2003" = "red",
"2004" = "orange", "2005" = "yellow", "2007" = "darkred",
"2008" = "purple", "2009" = "green", "2012" = "darkgreen"))
输出
数据
df <- structure(list(Mealtime = c("Breakfast", "Breakfast", "Breakfast", "Breakfast",
"Breakfast", "Breakfast", "Breakfast", "Breakfast",
"Breakfast", "Breakfast", "Breakfast"),
Food = c("Rashers", "Rashers", "Rashers", "Rashers", "Rashers",
"Rashers", "Rashers", "Rashers", "Rashers", "Rashers", "Rashers"),
variable = structure(1:11, .Label = c("2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010",
"2011", "2012"), class = "factor"),
value = c(9.12, 9.5, 2.04, -20.72, 18.37, 91.19, 94.83,
191.96,-125.3,-18.56, 63.85)),
row.names = c(NA, -11L), class = "data.frame")