如何用颜色填充箱形图?

时间:2020-04-01 09:43:07

标签: r ggplot2

我想创建四个彼此相邻的箱形图。它们都应该充满另一种颜色。我试过了:scale_fill_manual(values = c(“ 1” =“红色”,“ 2” =“绿色”,“ 3” =“黄色”,“ 4” =“蓝色”))

options(stringsAsFactors = FALSE) 
input <- "C:\\statistical_tests\\boxplot.csv" 
boxplot<- read.csv(input, sep=";") 

library(ggplot2) 
library(scales) 
means <- aggregate(number ~ CPOD, paper, mean) 
p <- ggplot(boxplot, aes(group=time,y=number, x=as.character(time))) +
     geom_boxplot()+ theme_bw() + 
     scale_fill_manual(values=c("1"="red", "2"="green", "3"="yellow", "4"="blue"))+ 
             panel.grid.minor=element_line(colour="white"), 
             axis.text.x = element_text(size=8, colour="black"),
             axis.text.y=element_text(size=8, colour="black")) 
print(p) 

很遗憾,它无法正常工作。 有人可以帮我吗? 非常感谢!

1 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

data("iris")
ggplot( iris, aes( x = Species, y = Sepal.Length, fill = Species ) ) +
  geom_boxplot()

请注意,仅当x轴变量是因子或字符时,此方法才有效。您可以在data.frame中对其进行定义,也可以如下所示进行实时处理。当您不想更改原始数据的结构时,这很有用。

data("iris")
ggplot( iris, aes( x = as.factor(Species), y = Sepal.Length, fill = Species ) ) +
  geom_boxplot()

enter image description here