我希望能够根据另一个变量 data_origin
更改 ggplot2 箱线图中的调色板。
这使我的箱线图完整并带有图例:
library(hrbrthemes)
library(ggplot2)
library(reshape2)
library(tidyverse)
data_origin <- "airborne"
mytitle <- "something more than this"
legend_title <- "some words"
melted <- reshape2::melt(iris)
bp1 <- ggplot(melted,aes(x = variable,y = value,fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable,scale = "free")
bp1
然而,这完全删除了图例并忽略了 if else
:
bp1 <- ggplot(melted,fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(legend_title,if (data_origin == "airborne" ) {palette = "Blues"} else {palette = "Greens"}) +
theme(
legend.position = "bottom",# legend.title = legend_title,plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable,scale = "free")
bp1