You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stata中twoway绘图如何保持分组颜色与原图一致?

问题描述

我用以下Stata代码处理数据:

sysuse nlsw88, clear
gen hours1 = inrange(hours, 1, 20)
replace hours1 = 2 if inrange(hours, 21, 39)
replace hours1 = 3 if inrange(hours, 40, 40)
replace hours1 = 4 if inrange(hours, 41, 80)
collapse (mean) wage, by(grade hours1)

接着绘制了包含所有分组的第一幅折线图:

twoway  (line wage grade if hours1==1) ///
        (line wage grade if hours1==2) ///
        (line wage grade if hours1==3) ///
        (line wage grade if hours1==4), ///
        legend(order(1 "1-20小时" 2 "21-39小时" 3 "40小时" 4 "41+小时"))

之后我绘制了省略第一组(hours1==1)的第二幅图:

twoway  (line wage grade if hours1==2) ///
        (line wage grade if hours1==3) ///
        (line wage grade if hours1==4), ///
        legend(order(1 "21-39小时" 2 "40小时" 3 "41+小时"))

我的需求是:让第二幅图的配色和第一幅图完全一致,即21-39小时组用红色、40小时组用绿色、41+小时组用黄色。

解决方案

有两种简单的方法可以实现这个需求:

方法一:手动指定对应颜色

直接在每个line绘图命令后添加color()参数,明确指定第一幅图中对应分组的颜色:

twoway  (line wage grade if hours1==2, color(red)) ///
        (line wage grade if hours1==3, color(green)) ///
        (line wage grade if hours1==4, color(yellow)), ///
        legend(order(1 "21-39小时" 2 "40小时" 3 "41+小时"))

方法二:通过颜色序列索引匹配

Stata的默认配色方案有固定的颜色序列,第一幅图中第2组对应序列的第2个颜色,第3组对应第3个,第4组对应第4个。可以用pcolor(n)来调用序列中第n个颜色,这样即使后续修改绘图scheme,颜色也会自动和原序列位置匹配:

twoway  (line wage grade if hours1==2, color(pcolor(2))) ///
        (line wage grade if hours1==3, color(pcolor(3))) ///
        (line wage grade if hours1==4, color(pcolor(4))), ///
        legend(order(1 "21-39小时" 2 "40小时" 3 "41+小时"))

内容的提问来源于stack exchange,提问作者bill999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:47:29