首页 > 解决方案 > 如何用颜色填充箱线图?

问题描述

我想创建四个相邻的箱线图。它们都应该用另一种颜色填充。我试过: scale_fill_manual(values=c("1"="red", "2"="green", "3"="yellow", "4"="blue"))

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) 

不幸的是,它不起作用。有人可以帮助我吗?非常感谢!

标签: rggplot2

解决方案


这可能是你想要的吗?

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()

在此处输入图像描述


推荐阅读