我正在尝试在r中的for循环内进行绘图,这是python中非常简单的任务。我想要一个基于3个不同值的参数的3个图。
我的代码
clust <- list(3,4,5)
for (i in clust)
set.seed(42)
k_clust = kmeans(
college_scaled,
centers = i,
nstart = 25
)
fviz_cluster(
k_clust,
data = college_scaled,
main = "Colleges Segmented by Average Faculty Salary and Tuition Rates",
geom= c("point","text"),
labelsize= 8,
pointsize= 1,
ggtheme= theme_minimal()
)
由于某种原因,它仅绘制centers = 5
,而不是遍历循环并绘制3,4和5。
答案 0 :(得分:2)
我没有college_scaled
数据可复制您的代码,因为块不同时包含k_clust
和fviz_cluster
命令。添加{
,}
,使两者保持循环:
clust <- list(3,4,5)
for (i in clust)
{
set.seed(42)
k_clust = kmeans(
college_scaled,
centers = i,
nstart = 25
)
print(
fviz_cluster(
k_clust,
data = college_scaled,
main = "Colleges Segmented by Average Faculty Salary and Tuition Rates",
geom= c("point","text"),
labelsize= 8,
pointsize= 1,
ggtheme= theme_minimal()
)
)
}
编辑:添加了基于starja的注释提醒打印内容。