在r中的for循环内绘制多个图

时间:2020-10-07 19:22:28

标签: r

我正在尝试在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。

1 个答案:

答案 0 :(得分:2)

我没有college_scaled数据可复制您的代码,因为块不同时包含k_clustfviz_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的注释提醒打印内容。