繁体   English   中英

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

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

我有一个带有类别列“颜色”的数据集,该列具有4种颜色。 其他2列之一是定量的,被称为“花粉”。 我正在尝试让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是否可以绘制花粉与颜色?

这是另一种不太重复的方式。 当您发现自己一遍又一遍地键入相同的内容时,例如这四行子集,这表明存在一种更有效的方法。

在这种情况下, 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()

在此处输入图片说明

子集化时,您拼错了“紫色”字样。 另外,在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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM