R语言STM包技术问询:按评级分组绘制主题流行度曲线
Absolutely! You can definitely add those two group-specific prevalence curves (for liberal and conservative ratings) to your STM topic time plot. The key is using the estimateEffect() function to model the interaction between time and your rating variable, then visualizing the results with ggplot2 for flexible customization. Here's a practical, code-driven breakdown:
Step 1: Estimate Group-Specific Topic Effects
First, you'll need to model how Topic 7's prevalence changes over time for each rating group. Assuming you already have your fitted STM model (let’s call it stm_model) and metadata (with year for time and rating as your liberal/conservative grouping variable):
library(stm) library(ggplot2) # Estimate the interaction effect of time and rating on Topic 7 effect_model <- estimateEffect( formula = 7 ~ s(year) * rating, # s(year) creates a smooth time trend; * includes group interaction stmobj = stm_model, meta = your_metadata, uncertainty = "Global" # Include confidence intervals for the estimates )
Step 2: Extract Plotting Data
Instead of relying on STM's default plot function, we’ll pull the underlying data to build our custom plot with ggplot2:
# Extract data for both liberal and conservative groups plot_data <- plot( effect_model, covariate = "year", method = "continuous", moderator = "rating", moderator.value = c("liberal", "conservative"), returnData = TRUE # Critical: returns a data frame instead of plotting directly )
Step 3: Build the Custom Plot
Use ggplot2 to create the plot with both group curves, plus optional shaded confidence intervals:
ggplot(plot_data, aes(x = year, y = mean, color = rating)) + # Add the main prevalence curves geom_line(linewidth = 1) + # Add shaded confidence intervals for each group geom_ribbon( aes(ymin = lower, ymax = upper, fill = rating), alpha = 0.2, color = NA # Remove ribbon border for a cleaner look ) + # Customize labels and theme labs( title = "Topic 7 Prevalence Over Time by Political Orientation", x = "Year", y = "Estimated Topic Prevalence", color = "Political Orientation", fill = "Political Orientation" ) + theme_minimal() + scale_color_manual(values = c("liberal" = "#1f77b4", "conservative" = "#ff7f0e")) # Optional: set custom group colors
Quick Tips
- Ensure your
ratingvariable is a factor in your metadata (useyour_metadata$rating <- factor(your_metadata$rating)if needed) so the groups are recognized correctly. - If you need to confirm Topic 7’s identity, run
labelTopics(stm_model)to check the top terms for each topic. - Adjust the
uncertaintyparameter inestimateEffect()if you want faster computation (use"Local"instead of"Global").
内容的提问来源于stack exchange,提问作者Hu_Ca

