如何将stm包两次searchK的绘图合并为带图例的单图
Hey there! Let's get those two plots combined into one clear, labeled figure. Here's a straightforward approach with custom colors and a legend:
Step-by-Step Solution
First, we'll create a single plotting canvas, add both datasets with distinct visual styles, then add a legend to distinguish them.
Full Combined Plot Code
# 先计算坐标轴的范围,确保两组数据都能完全显示 x_limits <- range(c(df1$results$K, df2$results$K)) y_limits <- range(c(df1$results$heldout, df2$results$heldout)) # 初始化绘图框架,以df1的数据为基础,设置全局标题和标签 plot(df1$results$K, df1$results$heldout, type = "p", main = "Held-Out Likelihood vs. Number of Topics", xlab = "Number of Topics (K)", ylab = "Held-Out Likelihood", col = "darkblue", # df1的点颜色 pch = 16, # df1的点样式(实心圆) xlim = x_limits, # 手动设置x轴范围 ylim = y_limits) # 手动设置y轴范围 # 添加df1的线条 lines(df1$results$K, df1$results$heldout, lty = 1, col = "darkblue") # 添加df2的点和线条,用不同颜色和样式区分 points(df2$results$K, df2$results$heldout, col = "darkred", pch = 17) # df2的点样式(实心三角形) lines(df2$results$K, df2$results$heldout, lty = 2, col = "darkred") # 在右上角添加图例 legend("topright", legend = c("likelihood_score_df1", "likelihood_score_df2"), col = c("darkblue", "darkred"), lty = c(1, 2), pch = c(16, 17), bty = "n") # 去掉图例边框,让图表更简洁(可选)
What Each Part Does
- Axis Range Calculation: We first get the min/max values for both K and held-out likelihood across both datasets, so the plot will fit all points without cutting anything off.
- Initial Plot: We start with df1's points, setting the title, axis labels, and a unique color/point style for this dataset.
- Adding Lines: We add solid lines for df1 and dashed lines for df2 to make the trends easy to follow.
- Legend: The legend in the top-right corner clearly maps each color/style to its corresponding dataset, so anyone reading the plot can instantly tell them apart.
If you want to tweak the colors, point styles, or line types, just adjust the col, pch, and lty parameters to your preference!
内容的提问来源于stack exchange,提问作者Nathalie
相关产品推荐
相关产品推荐

