Stata中Sepscatter图添加Lowess平滑曲线并保留区域标签的实现方案
The Problem You Faced
You wanted to create a single scatter plot showing all regions (with distinct markers per region) and overlay Lowess smoothing curves—but your first attempt using twoway ... by(region) split the data into separate panels for each region, which wasn't what you needed.
The Fix: Using sepscatter with addplot
Thanks to Nick's suggestion, here's how to get the combined plot with Lowess curves while keeping all regions on one graph. We'll cover two common use cases:
Case 1: Single Overall Lowess Curve (Fits All Data)
If you want one smoothing curve that represents the entire dataset (across all regions):
sepscatter avg_unemp log_avg_gdp, separate(region) addplot(lowess avg_unemp log_avg_gdp)
sepscatterhandles grouping regions by marker style, keeping everything on one graph.addplot(lowess ...)overlays the overall smooth curve directly on top.
Case 2: Region-Specific Lowess Curves (One per Region)
If you want a unique smoothing curve for each region (matching their marker groups):
sepscatter avg_unemp log_avg_gdp, separate(region) /// addplot( /// lowess avg_unemp log_avg_gdp if region=="Middle East & North Africa", lcolor(#8b0000) /// || lowess avg_unemp log_avg_gdp if region=="Latin America & Caribbean", lcolor(#006400) /// || lowess avg_unemp log_avg_gdp if region=="Europe & Central Asia", lcolor(#0000ff) /// || lowess avg_unemp log_avg_gdp if region=="Sub-Saharan Africa", lcolor(#800080) /// || lowess avg_unemp log_avg_gdp if region=="East Asia & Pacific", lcolor(#ff8c00) /// || lowess avg_unemp log_avg_gdp if region=="South Asia", lcolor(#a52a2a) /// || lowess avg_unemp log_avg_gdp if region=="North America", lcolor(#000000) /// ) /// legend(expand)
- Each
lowesscommand inaddplotis filtered to a single region usingif region=="...". - Assign distinct
lcolorvalues to each curve so they match the region markers in the legend (uselegend(expand)to ensure all entries show up).
Why Your Initial twoway by(region) Didn't Work
The by(region) option in twoway tells Stata to generate a separate subplot (panel) for each region. That's great for side-by-side comparisons, but not when you want all data on one graph. sepscatter is purpose-built for combined plots with group differentiation, making it the right tool here.
内容的提问来源于stack exchange,提问作者nesta13

