R 通过在ggplot中的一个图上指定的聚类,对不同变量进行箱线图
我正试图找出一种方法,从ggplot中的base R绘制以下代码:R 通过在ggplot中的一个图上指定的聚类,对不同变量进行箱线图,r,ggplot2,boxplot,R,Ggplot2,Boxplot,我正试图找出一种方法,从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) } fit您可以将data.frame重塑为长格式(此处使用tidyr::gather)并使用facet\u网格 library(
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)
}
fit您可以将data.frame重塑为长格式(此处使用tidyr::gather
)并使用facet\u网格
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(tidyr)
comp.df.long这个应该有帮助
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)
有点长,更多的手动操作,但也有这个简单的方法。更长,但如果您想为每个图形使用不同的颜色或大小,它会为您提供更大的灵活性
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)
库(ggplot2)
图书馆(gridExtra)
测试MLavoie,您的解决方案很好,因为它可以让您更好地控制格式,正如您所提到的。但如果有5个以上的变量,这会很麻烦。我喜欢CAFEBABE的解决方案,但不知道是否有办法避免重塑数据。我的7MB数据集(100K行)很快就被重塑为11MB数据集(700K行),但如果可能,最好避免这一步。
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)