在 ggplot 中的一张图上分配的不同变量的箱线图

Boxplots of different variables by cluster assigned on one graph in ggplot

我正在尝试找出一种方法来在 ggplot 中从 base R 绘制以下代码:

fit <- kmeans(iris[,-5], 3)

par(mfrow=c(1,4))
for (i in 1:4) {
  boxplot(iris[,i]~fit$cluster, xlab="Cluster",
  ylab=names(iris)[i], varwidth=T)
}

我有一种预感,有一种方法可以避免在 ggplot 中使用循环来绘制它,但我不知道如何实现。到目前为止,我只绘制了一个变量。我将使用什么来按集群绘制所有数字变量的箱线图?

par(mfrow=c(1,1))
comp.df <- cbind(iris, fit$cluster)
names(comp.df)[6] <- "cluster"

comp.df$cluster <- as.factor(comp.df$cluster)

test <- ggplot(comp.df, aes(x = cluster, y = Sepal.Length)) + 
  geom_boxplot()

也许这是其中一个基数 r 更适合绘图的例子。

您可以将 data.frame 重塑为长格式(此处使用 tidyr::gather)并使用 facet_grid

library(tidyr)
comp.df.long <- gather(comp.df,key,value,-Species,-cluster)
ggplot(comp.df.long, aes(x = cluster, y = value)) + 
  geom_boxplot() +
  facet_grid(.~key)

这个应该有帮助

 library(reshape2)
 melted<- melt(comp.df[c(1:4,6)],id.vars="cluster")
 ggplot(melted, aes(x = cluster, y = value)) + 
     geom_boxplot()+facet_wrap(~variable)

关键元素是facet_wrap,类似于SQL中的group by。基本上每个 "variable" 完成一个图。 melt 命令将您的数据从宽格式转换为长格式。这意味着不同的特征不是更长的列,而是你有一个值和一个变量列

head(melted)



cluster     variable value
1       1 Sepal.Length   5.1
2       2 Sepal.Length   4.9
3       2 Sepal.Length   4.7
4       2 Sepal.Length   4.6
5       1 Sepal.Length   5.0
6       1 Sepal.Length   5.4

有点长,比较手动,不过也有这个简单的方法。更长,但如果您想为每个图表使用不同的颜色或大小,它会为您提供更大的灵活性。

library(ggplot2)
library(gridExtra)
test <- ggplot(comp.df, aes(x = cluster, y = Sepal.Length)) + 
  geom_boxplot() + theme_bw()

testb <- ggplot(comp.df, aes(x = cluster, y = Sepal.Width)) + 
  geom_boxplot() + theme_bw()

testc <- ggplot(comp.df, aes(x = cluster, y = Petal.Length)) + 
  geom_boxplot() + theme_bw()

testd <- ggplot(comp.df, aes(x = cluster, y = Petal.Width)) + 
  geom_boxplot() + theme_bw()
grid.arrange(test, testb, testc, testd, nrow=1)