如何在 R 中使用 vioplot 绘制分类数据与数值数据?

How to plot categorical vs numerical data with vioplot in R?

我有一个包含分类列 "colors" 的数据集,它有 4 种颜色。其他 2 列中的一列是定量的,称为 "pollen"。我想让 vioplot 制作 4 个独立的小提琴图颜色与花粉。这是一个数据样本

数据可在 http://www.uwyo.edu/crawford/datasets/beeflowers.txt

我用

制作了 4 个数据子集
blue <- subset(beeflowers4, colors=="blue", select=c(pollen, colors))
green <- subset(beeflowers4, colors=="green", select=c(pollen, colors))
purple <- subset(beeflowers4, colors=="pruple", select=c(pollen, colors))
red <- subset(beeflowers4, colors=="red", select=c(pollen, colors))

然后我尝试用

绘制小提琴情节
vioplot(blue, green, purple, red, names=c("blue", "green", "purple", "red"), col="yellow")

但是我得到了这个错误

#Error in FUN(X[[1L]], ...) : 
#  only defined on a data frame with all numeric variables

vioplot 是否有绘制花粉与颜色的关系图?

您在子集化时拼写错误 "purple"。此外,在 vioplot 函数中,前四个参数必须是向量,而不是数据帧。此代码应该有效。

blue <- subset(beeflowers4, colors=="blue", select=c(pollen, colors))

green <- subset(beeflowers4, colors=="green", select=c(pollen, colors))

purple <- subset(beeflowers4, colors=="purple", select=c(pollen, colors))

red <- subset(beeflowers4, colors=="red", select=c(pollen, colors))

vioplot(blue$pollen, green$pollen, purple$pollen, red$pollen, names=c("blue", "green", "purple", "red"), col="yellow")

这是另一种重复次数少得多的方法。当您发现自己一遍又一遍地输入相同的内容(例如那四行子集)时,这表明存在更有效的方法。

在这种情况下,ggplot 会采用您已有的长格式数据,因此无需进行任何子设置或整形。

# import data
x <- read.table("http://www.uwyo.edu/crawford/datasets/beeflowers.txt", 
                stringsAsFactors = FALSE,
                header = TRUE)

# inspect
str(x); View(x)

# get rid of that 999, presumably missing data
x <- x[x$pollen != 999, ]

# plot
library(ggplot2)
ggplot(x, aes(colors, pollen)) +
  geom_violin()