Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 通过在ggplot中的一个图上指定的聚类,对不同变量进行箱线图_R_Ggplot2_Boxplot - Fatal编程技术网

R 通过在ggplot中的一个图上指定的聚类,对不同变量进行箱线图

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(

我正试图找出一种方法,从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(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)