首页 > 解决方案 > 在 R 中为 Boxplot 添加颜色

问题描述

boxplot(mtcars$mpg ~ mtcars$cyl, main = "Box Plot of Mileage vs Number of Cylinders", xlab = "Number of Cylinders", ylab = "Miles per Gallon", col = "lightgreen")

我有这个代码,所有的盒子都是绿色的,我可以添加什么来使盒子颜色不同

标签: r

解决方案


您只需要为颜色添加一个因子(x_axis_var)。

boxplot(mtcars$mpg ~ mtcars$cyl, 
        main = "Box Plot of Mileage vs Number of Cylinders", 
        xlab = "Number of Cylinders", 
        ylab = "Miles per Gallon", col = factor(mtcars$cyl))

或提供颜色向量:

boxplot(mtcars$mpg ~ mtcars$cyl, 
        main = "Box Plot of Mileage vs Number of Cylinders", 
        xlab = "Number of Cylinders", 
        ylab = "Miles per Gallon", col = c("blue","red","green"))

推荐阅读