如何将stm包searchK生成的合并图拆分为4个带原标签的独立图?
拆分stm包searchK合并图为独立子图的方法
刚好我之前也处理过类似的需求,stm包的searchK()默认生成的2x2合并图没法直接拆分,但我们可以手动提取返回结果里的原始数据,自己绘制每个带对应标签的独立图表,具体步骤如下:
1. 先明确合并图里的四个子图对应的数据
searchK()返回的df1对象里,df1$results包含了所有绘图需要的核心数据:
- 语义连贯性(Semantic Coherence):
df1$results$semcoh - 排他性(Exclusivity):
df1$results$exclus - 持有可能性(Heldout Likelihood):
df1$results$heldout - 残差(Residuals):
df1$results$residuals - 对应的K值:
df1$results$K
2. 用基础R绘图生成独立子图
先提取所需数据,再逐个绘制每个指标的独立图:
# 从df1中提取绘图数据 k_values <- df1$results$K sem_coh <- df1$results$semcoh exclusivity <- df1$results$exclus heldout_likelihood <- df1$results$heldout residuals <- df1$results$residuals # 1. 语义连贯性图(对应原合并图左上) plot(k_values, sem_coh, type = "b", pch = 16, xlab = "Number of Topics (K)", ylab = "Semantic Coherence", main = "Semantic Coherence by Number of Topics") # 2. 排他性图(对应原合并图右上) plot(k_values, exclusivity, type = "b", pch = 16, xlab = "Number of Topics (K)", ylab = "Exclusivity", main = "Exclusivity by Number of Topics") # 3. 持有可能性图(对应原合并图左下) plot(k_values, heldout_likelihood, type = "b", pch = 16, xlab = "Number of Topics (K)", ylab = "Heldout Likelihood", main = "Heldout Likelihood by Number of Topics") # 4. 残差图(对应原合并图右下) plot(k_values, residuals, type = "b", pch = 16, xlab = "Number of Topics (K)", ylab = "Residuals", main = "Residuals by Number of Topics")
3. (可选)用ggplot2绘制更美观的独立子图
如果你偏好ggplot2的风格,可以把数据整理成数据框后逐个绘制:
library(ggplot2) # 整理成适合ggplot2的长格式数据框 plot_data <- data.frame( K = rep(k_values, 4), Value = c(sem_coh, exclusivity, heldout_likelihood, residuals), Metric = rep(c("Semantic Coherence", "Exclusivity", "Heldout Likelihood", "Residuals"), each = length(k_values)) ) # 绘制语义连贯性图 ggplot(plot_data[plot_data$Metric == "Semantic Coherence", ], aes(x = K, y = Value)) + geom_line(color = "#2c3e50", linewidth = 1) + geom_point(color = "#e74c3c", size = 3) + labs(x = "Number of Topics (K)", y = "Semantic Coherence", title = "Semantic Coherence by Number of Topics") + theme_minimal() # 绘制排他性图 ggplot(plot_data[plot_data$Metric == "Exclusivity", ], aes(x = K, y = Value)) + geom_line(color = "#2c3e50", linewidth = 1) + geom_point(color = "#e74c3c", size = 3) + labs(x = "Number of Topics (K)", y = "Exclusivity", title = "Exclusivity by Number of Topics") + theme_minimal() # 绘制持有可能性图 ggplot(plot_data[plot_data$Metric == "Heldout Likelihood", ], aes(x = K, y = Value)) + geom_line(color = "#2c3e50", linewidth = 1) + geom_point(color = "#e74c3c", size = 3) + labs(x = "Number of Topics (K)", y = "Heldout Likelihood", title = "Heldout Likelihood by Number of Topics") + theme_minimal() # 绘制残差图 ggplot(plot_data[plot_data$Metric == "Residuals", ], aes(x = K, y = Value)) + geom_line(color = "#2c3e50", linewidth = 1) + geom_point(color = "#e74c3c", size = 3) + labs(x = "Number of Topics (K)", y = "Residuals", title = "Residuals by Number of Topics") + theme_minimal()
这样就能得到四个和原合并图标签一致的独立图表啦,每个图都可以单独保存或调整样式。
内容的提问来源于stack exchange,提问作者Nathalie
相关产品推荐
相关产品推荐

