如何更改背景颜色并为小提琴图添加网格?

时间:2018-01-06 20:04:19

标签: r plot

我想改变小提琴情节背后的颜色,我想添加网格,但也要在小提琴后面。我试过这个:

library(vioplot)
par(mai=c(0.65,0.65,0.1,0.1), bg="lightblue", lwd=2, col="blue", 
col.axis="blue", las=1, cex.axis=1, cex.lab=1, col="red")
x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]

vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"),
    col="green", border="blue", lwd = 2, lty=3, rectCol="black", colMed = 
    "orange")
grid(nx = NULL, ny = NULL, col = "black", lty = "dotted")
axis(1, labels = NA, col="blue", col.ticks="blue", lwd=2)
axis(2, labels = NA, col="blue", col.ticks="blue", lwd=2)
title(ylab = expression(bold("MPG")), xlab=expression(bold("CYL")), line = 
2, col.lab="blue")

我得到了这个情节: enter image description here

但我想要这个小提琴情节: enter image description here

有人能帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:3)

使用dplyrggplot2,您只需

即可实现
library(ggplot2)
library(dplyr)

# Filter only "cyl" you want, i.e., 4, 6 and 8
data = mtcars %>%
       filter(cyl %in% c(4, 6, 8))

ggplot(data, aes(x=factor(cyl), y=mpg, fill=factor(cyl))) + 
  ylab("MPG") +
  xlab("CYL") + 
  geom_violin() +
  geom_boxplot(width=0.1) +
  theme(panel.background = element_rect(colour='blue', fill = 'lightblue'),
        plot.background = element_rect(fill = 'red'),
        axis.text.x = element_text(colour='blue'), 
        axis.text.y = element_text(colour='blue'),
        legend.position="none")

结果将类似于

enter image description here

答案 1 :(得分:2)

试试这个:

library(vioplot)

par(mai=c(0.65,0.65,0.1,0.1), bg="red", lwd=2, col="blue", 
    col.axis="blue", las=1, cex.axis=1, cex.lab=1, col="#ff4040")

x1 <- mtcars$mpg[mtcars$cyl==4]
x2 <- mtcars$mpg[mtcars$cyl==6]
x3 <- mtcars$mpg[mtcars$cyl==8]

vioplot(x1, x2, x3)
u <- par("usr")
rect(u[1], u[3], u[2], u[4], col = "lightblue", border = "blue")
grid(nx = NULL, ny = NULL, col = "black", lty = "dotted")
vioplot(x1, x2, x3, names=c("4 cyl", "6 cyl", "8 cyl"),add=T,
        col="green", border="blue", lwd = 2, lty=3, rectCol="black", colMed = 
          "orange")