Stata绘图:世行可视化案例-条形图-密度函数图-地图-断点回归图-散点图

发布时间:2021-02-23 阅读 13326

Stata连享会   主页 || 视频 || 推文 || 知乎

温馨提示: 定期 清理浏览器缓存,可以获得最佳浏览体验。

New! lianxh 命令发布了:
随时搜索连享会推文、Stata 资源,安装命令如下:
. ssc install lianxh
使用详情参见帮助文件 (有惊喜):
. help lianxh

课程详情 https://gitee.com/arlionn/Course   |   lianxh.cn

课程主页 https://gitee.com/arlionn/Course

作者: 万莉 (北京航空航天大学)
E-Mail: wanli_buaa@163.com

Source: Stata-IE-Visual-Library项目主页 提供了大量 Stata 绘图可视化案例和代码。

注:本推文相关数据,do file 及资料获取方式如下:

  1. 百度云盘:https://pan.baidu.com/s/1eROYRAoBMA9697VMRRrCkA, 提取码: o1mz
  2. 项目主页:https://gitee.com/arlionn/Stata-IE-Visual-Library,进入后,点击右上角的【Fork】按钮,可以把这个项目完整复制到你的码云账号下,随时查看。亦可单击【克隆/下载】按钮,将项目代码下载到本地。


目录


1. 引言

本文参考 GitHub 项目 Stata-IE-Visual-Library 提供的数据及代码,节选部分 Stata 范例来说明如何“用图展示数据和结果”。

本文可看作 Stata 绘图进阶篇。在学习本文案例时,不用太纠结弄懂原始数据中变量的定义(原作者并没提供足够的数据说明),只需借鉴案例中用到的命令。每节的基本结构为:展示完整的 Stata 范例(代码+部分注释)-- 展示输出的图 -- 重点强调并解释部分语法。

若你还不太熟悉 Stata 绘图命令,可先参考 一文看尽 Stata 绘图 这篇推文,了解基本语法结构。

2. 基本语法结构

便于大家快速掌握本文的 Stata 范例,本小节仍占用一点篇幅介绍 Stata 绘图的基本语法结构。若你已熟悉绘图命令,可跳过本小节内容。

基本语法结构如下:

graph-command (plot-command, plot-options)  ///
              (plot-command, plot-options)  ///
              (...),                        ///
              graph-options

graph-command plot-command, plot-options ||  ///
              plot-command, plot-options ||  ///
              ...,                           ///
              graph-options

具体说明如下:

  • graph-command 定义图的类型
  • plot-command 定义曲线类型(比如点、线、面等)
  • 同一个图中如果有多条曲线,可以用 “()” 分开, 也可以用 “||” 分开。
  • 不同的图类有其自身的选项,而整个图也有相应的选项。

例如: twowaygraph-command 中的一个子命令,而 scatter 则为 plot-command 的子命令,则可写成 graph twoway scatter mpg weight,亦可简写为 twoway scatter mpg weightscatter mpg weight

注意:()|| 分隔的 plot-command, plot-options 可看做一个图层。多个图层可进行叠加。

一个简单的例子如下:

/* 一个简单的例子 */
sysuse sp500, clear // 导入软件自带数据文件
#d ;
twoway (line high date) (line low date),
 title("这是图选项:标题", box)
 subtitle("这是副标题""图1:股票最高价与最低价时序图")
 xtitle("这是 x 轴标题:交易日期", margin(medsmall))
 ytitle("这是 y 轴标题:股票价格")
 ylabel(900(200)1400) ymtick(##5)
 legend(title("图例")label(1 "最高价") label(2 "最低价"))
 note("这是注释:数据来源于 Stata 公司")
 caption("这是说明:欢迎加入 Stata 连享会!")
 saving(myfig.gph, replace);
#d cr
/* 
Notes:
- line 是曲线选项,表示线图
- 设置副标题时,用 "" 达到换行效果
- ylabel 设置 y 轴标签及刻度
- saving() 表示保存图像
- #d ;  #d cr 表示断行,也可以用 ///
*/

运行结果见下图:

3. 条形图 (Bar plots)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/Bar plots

3.1 合并带双坐标系的条形图

* Figure: combined bar plots with two axes

* 1. 加载数据
use "Bar plots\Combined bar plots with two axes\data.dta",clear

* 2. 生成一个过渡变量 x,用以调整柱状位置
gen x = int1mo+.5
// intlmo是数值变量,表示月份,取值1-12

* 3. 利用循环语句+暂元逐个绘制双坐标系条状图
// foodGroup 变量表示食品种类
foreach foodGroup in animal fruit grain ///
            veg starch processed_sugar {
  if "`foodGroup'" == "animal"	///
      local graphTitle Animal Sourced
  if "`foodGroup'" == "fruit" ///
      local graphTitle Fruit
  if "`foodGroup'" == "grain" ///
      local graphTitle Grain
  if "`foodGroup'" == "veg"	///
     local graphTitle Vegetables
  if "`foodGroup'" == "starch" ///
     local graphTitle Starchy Foods
  if "`foodGroup'" == "processed_sugar"	///
     local graphTitle Processed/Sugar
  // 利用暂元存储标题名称

  qui twoway bar number_group x if food_group=="`foodGroup'", ///
      yaxis(1) ytitle("Avg. Number of Foods from" "Group Consumed Last Month", axis(1)) ///
      barwidth(.9) fintensity(inten0) lcolor(black) ///
      xlabel(0 "0" 3 "3" 6 "6" 9 "9" 12 "12") ///
      ylabel(0 "0" 1 "1" 2 "2" 3 "3", axis(1)) || ///
      line total_exp int1mo if food_group=="`foodGroup'", ///
      yaxis(2) ytitle("Total Value of Exp." "1000 Real Tz Sh.", axis(2)) ///
      ylabel(0 "0" 500 "500" 1000 "1000" 1500 "1500" 2000 "2000" 2500 "2500", axis(2)) ///
      xlabel(3 "3" 6 "6" 9 "9" 12 "12") lwidth(1.2) ///
      title("`graphTitle'") xtitle("Month of Interview") ///
      graphregion(color(white)) bgcolor(white) ///
      legend(off) ///
      name("`foodGroup'")
   /*
   qui 表示悄悄处理命令,不显示结果
   /// 表示换行,避免一行内容过多
   yaxis(1) yaxis(2) 表示双纵坐标
   fintensity()设置填充颜色的饱和程度(取值:0-100)
   lcolor() 设置柱子的外边缘线的颜色
   barwidth() 设置柱子的显示宽度
   graphregion() 设置图外围的颜色
   bgcolor() 设置背景颜色
   name() 给每个图命名,便于后续的调用
   */
}

* 4. 图形合并
graph combine starch animal fruit grain processed_sugar veg, ///
      graphregion(color(white)) plotregion(color(white))

* 5. 保存图片
graph export "figure.png", as(png) replace

绘制的图如下:

语法要点:

3.2 横向条形图

* Figure: horizontal bar plot

* 1. 将图像的基本设置保存在全局暂元 graph_opts1 里
global graph_opts1 bgcolor(white) graphregion(color(white)) ///
       legend(region(lc(none) fc(none))) ///
       ylab(,angle(0) nogrid) ///
       title(, justification(left) color(black) span pos(11)) ///
       subtitle(, justification(left) color(black))


* 2. 加载数据
use "Bar plots\Horizontal bar plot\data1.dta" , clear
keep facilitycode study hours // 保存感兴趣的变量

// ---------开始----------
tempfile vietnam // 生成临时性文件,程序结束自动删除
save `vietnam' , replace

use "Bar plots\Horizontal bar plot\data2.dta" , clear //印度数据
gen hours = tottime/60
drop tottime

append using `vietnam' //合并数据
// -----------结束-----------
// 由于临时性文件运行一次即自动删除,需要连续运行

* 3. 横向条形图
graph bar hours , $graph_opts1 over(study) ///
      blabel(bar, format(%9.1f)) ///
      hor ylab(1 "1 Hour" 2 "2 Hours" 3 "3 Hours") ///
      bar(1,fi(100) lc(black) lw(thin)) ///
      ytit("Average Daily Time Seeing Patients {&rarr}", ///
           placement(left) justification(left))

* 4. 保存图片
graph export "figure.png" , replace width(1000)

绘制的图如下:

语法要点:

  • hor 表示横向展示条形图;
  • bar(1, ...) 对所有柱体设置填充颜色、边框颜色、边框线条等。

3.3 横向堆叠条形图

* Figure: horizontal stack bar plot
* 1. 利用全局暂元保存图像的基本设置
global graph_opts1 ///
       title(, justification(left) color(black) span pos(11)) ///
       graphregion(color(white) lc(white)) ///
       ylab(,angle(0) nogrid)  ///
       yscale(noline) legend(region(lc(none) fc(none)))

global pct `" 0 "0%" .25 "25%" .5 "50%" .75 "75%" 1 "100%" "'

* 2. 加载数据
use "Bar plots\Horizontal stack bar plot\data2.dta", clear

* 3. 绘制横向堆叠条形图
graph bar (sum) theResults1 theResults2 theResults3 theResults4 theResults5, ///
    ylab($pct) $graph_opts1 hor stack over(n) xsize(6) ///
    bar(1, lc(black) lw(thin)) ///
    bar(2, lc(black) lw(thin)) ///
    bar(3, lc(black) lw(thin)) ///
    bar(4, fc(black) lc(black) lw(thin)) ///
    bar(5, fc(gs12) lc(black) lw(thin)) ///
    legend(pos(5) ring(0) c(1) symxsize(small) symysize(small)  ///
    order(6 "Variance Explained By:" ///
          1 "City Setting" ///
          2 "Case Scenario" ///
          3 "MBBS Degree" ///
          4 "All SP Characteristics" ///
          5 "Full Interaction Model"  ))

* 4. 输出图像
graph export "figure.png" , replace width(1000)

绘制的图如下:

语法要点:

  • over(...) 表示按什么变量进行分组;
  • hor 表示横向展示条形图;
  • stack 表示堆叠;
  • bar(#, ...) 对第 # 个堆叠成分设置填充颜色、边框颜色、边框线条等;
  • legend(...,order(...)) 设置图例文字。

4. 密度函数图 (Density plots)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/Density plots

4.1 附加竖线的核密度函数图

* Figure: Density plots with averages

* 1. 加载数据
use "Density plots\Density plot with averages\data.dta", clear

* 2. 计算均值
sum revenue if post == 0
local pre_mean = r(mean)
sum revenue if post == 1
local post_mean = r(mean)

* 3. 绘制核密度函数图
twoway 	(kdensity revenue if post == 0, color(gs10)) ///
        (kdensity revenue if post == 1, color(emerald)), ///
        xline(`pre_mean', lcolor(gs12) lpattern(dash)) ///
        xline(`post_mean', lcolor(eltgreen) lpattern(dash)) ///
        legend(order(1 "Pre-treatment" 2 "Post-treatment")) ///
        xtitle(Agriculture revenue (BRL thousands)) ///
        ytitle(Density) ///
        bgcolor (white) graphregion(color(white))
// 由于局部暂元 local 的存在,第 2,3 部分代码必须一起运行
// 否则报错

* 4. 输出图片
gr export "figure.png", width(5000) replace

绘制的图如下:

语法要点:

  • xline(...) 是在绘制的图像基础上附加一条竖直线;
    • 其中,lcolor 设定线条的轮廓颜色;
    • lpattern 设定线条的类型,比如虚线;
    • 在本例中,竖线表示了数据的均值。

4.2 带数据点的核密度函数图

* Figure: Density graph with data points
* 1. 用全局暂元设定图像设置
clear all
global graph_opts //
  title(, justification(left) color(black) span pos(11)) ///
  graphregion(color(white)) ///
  ylab(,angle(0) nogrid notick) ///
  xscale(noline) yscale(noline) yline(0 , lc(black)) ///
  xtit(,placement(left) justification(left)) ///
  legend(region(lc(none) fc(none)))

global hist_opts
  ylab(, angle(0) axis(2)) yscale(noline alt axis(2)) ///
  ytit(, axis(2)) ytit(, axis(1)) yscale(off axis(2)) yscale(alt)

* 2. 加载数据
use "Density plots\Density plot with data points\data.dta"  , clear

* 3. 创建画图需要的数据
qui su theta_mle
gen score = theta_mle - `r(min)'
gen bach = roster_6a8 > 4 //生成0-1虚拟变量

tw ///
  (kdensity score if bach == 0 , lp(dash) lc(maroon) yaxis(2)) ///
  (kdensity score if bach == 1 , lp(dash) lc(navy) yaxis(2)) ///
  (histogram score if bach == 0 , freq w(.1) ///
     recast(scatter) msize(small) mc(maroon)) ///
  (histogram score if bach == 1 , freq w(.1) ///
     recast(scatter) msize(small) mc(navy)),  ///
  legend(symxsize(small) ///
    order(0 "" 0 "" 0 "{bf: Degree:}" ///
          3 "Intermediate, Undergrad, or Bachelors (N=575)" ///
          4 "Specialist or Masters (N=431)") ///
          c(1) pos(11) ring(0))  ///
  $graph_opts $hist_opts ///
  xtit("Knowledge Score {&rarr}") ///
  xlab(0(1)7) ///
  yline(10 20 30 , lc(gs12) lp(dot)) ///
  xsize(7)
// tw 为 twoway 的缩写
// 你可以把 $graph_opts $hist_opts 删掉看看差异

* 4. 输出图片
graph export "figure.png" , replace width(1000)

绘制的图如下:

语法要点:

  • kdensity 为核密度函数图绘制命令;
  • recast(scatter) 是将直方图变成散点形式;
  • msize(small) 设置散点形状的大小;
  • mc(maroon) 设置散点的填充颜色;
  • order(0 "") 的效果相当于在图例中增加了空行。

4.3 附加阴影的核密度函数图

*Figure: Shaded k-density functions

* 0. 安装外部命令
ssc install akdensity

* 1. 加载数据
use "Density plots\Shaded k-density functions\data.dta", clear

* 2. 创建画图用的变量
sort beta_ // 2sls回归系数
gen rank = _n

* 3. 绘制 Adaptive Kernel Density
egen p98=pctile(beta_), p(98)

sum beta_, det
local mean = round(`r(mean)', .00001)
local median = round(`r(p50)', .00001)

/*
Graph: DISTRIBUTION OF 2SLS COEFFICIENT ESTIMATES
       USING RANDOMIZED FOOD AID ALLOCATIONS

akdensity0 comes from the package "akdensity"
*/
akdensity0 beta_, gen(x) at(beta_) bwidth(.0005)

sum beta_, d // 描述性统计

twoway ///
  area x beta_ if rank>15 & beta_<(`r(p10)'), color(gs14) || ///  // 低于10%的浅色阴影
  area x beta_ if beta_>`r(p90)' & rank<980, color(gs14) || ///  // 高于90%的浅色阴影
  area x beta_ if rank>15 & beta_<(`r(p5)'), color(gs9) || /// // 低于5%的深色阴影
  area x beta_ if beta_>`r(p95)' & rank<980, color(gs9) || /// // 高于95%的深色色阴影
  line x beta_ if rank>15  & rank<980, lcolor(black) || ///  // 绘制核密度,x 为估计出的密度
  (pcarrowi -20 .00299 310 .00299, lcolor(cranberry) lpattern(dash) msize(zero)) || ///  // 绘制竖线,标示N&Q的系数
  (pcarrowi -20 `r(mean)' 310 `r(mean)', lcolor(gs7) lpattern(dash) msize(zero)) || ///  // 绘制竖线,标示BS的均值
  (pcarrowi -20 `r(p50)' 310 `r(p50)', lcolor(gs7) lpattern(dash) msize(zero)), /// // 绘制竖线,标示BS的中位数
  legend(off) ///
  xtitle("2SLS Coefficient from baseline model" " ") ///
  ytitle("Density" " ") ///
  xlabel(0 "0" .00299 "NQ=.00299"  ///
        `r(p50)' "Median=`median'" ///
        `r(mean)' "Mean=`mean'" ///
        .015 ".02", angle(45)) ///
  ylabel(none) ///
  bgcolor(white) graphregion(color(white))

* 输出图片
graph export "figure.png", as(png) replace

绘制的图如下:

语法要点:

  • akdensity0 为外部命令,来自 akdensity 这个包,用以估计自适应的核密度 (Adaptive Kernel Density);
  • area 命令可用来绘制阴影区域;
  • pcarrowi 可用来绘制竖直线,也可用来绘制带箭头的线或流程图。

5. 线图 (Line plots)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/Line plots

5.1 附加置信区间的拟合曲线

*Figure: Line plots witthed line with confidence interval

* 1. 加载数据
use "Line plots\Line plots\data.dta", clear

* 2. 估计处理效应
reg y_var x_var post x_var_post control

* 3. 保存需要用以画图的系数和 F 检验的 P 值
local beta_pre  = round(_b[x_var],0.001)
local beta_post = round(_b[x_var] + _b[x_var_post],0.001)

test _b[x_var_post] = 1
local f_pre = round(r(p),0.001)
if `f_pre' == 0 local f_pre = "0.000"

test _b[x_var_post] + _b[x_var_post] = 1
local f_post = round(r(p),0.001)

* 4. 绘图
twoway ///
  (lfitci y_hat x_var if post == 1, color("222 235 247") lwidth(.05)) ///
  (lfitci y_hat x_var if post == 0, color(gs15)) ///
  (lfit	x_var x_var	if post == 1, color(red) lwidth(.5) lpattern(dash)) ///
  (lfit y_hat x_var	if post == 0, color(gs8) lwidth(.5)) ///
  (lfit y_hat x_var	if post == 1, color(edkblue) lwidth(.5)), ///
  text(5 9 "Pre-treatment" "Regression coefficent: 0`beta_pre'" "P-value of coefficent = 1: `f_pre'" ///
  12 9 "Post-treatment" "Regression coefficent: 0`beta_post'" "P-value of coefficent = 1: 0`f_post'", ///
  orient(horizontal) size(vsmall) justification(center) fcolor(white) box margin(small)) ///
  xtitle("Independent variable value") ///
  ytitle("Predicted value of dependent variable") ///
  legend(order (6 "Pre-treatment" 7 "Post-treatment" 3 "Pre-treatment 95%CI" 1 "Pre-treatment 95%CI")) ///
  graphregion(color(white)) bgcolor(white)

* 5. 保存图片
gr export "figure.png", width(5000) replace

绘制的图如下:

语法要点:

  • lfitci 绘制线性回归拟合的置信区间;
  • lfit 绘制线性回归拟合的直线;
  • text 在图中添加文字说明。

6. 地图 (Maps)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/Maps

6.1 世界分级统计地图

在分级统计地图中,每个区域以不同深浅度的颜色表示数据变量。此法因常用色级表示,所以也叫色级统计图法。

* Maps displaying levels of a variable

* ---------------------------
* 1. 安装外部命令
* ---------------------------
ssc install spmap
ssc install shp2dta

* ---------------------------
* 2. 加载数据
* ---------------------------
cd "$path\Maps\Map displaying levels of a variable"

*Shapefiles
cap erase world_shape.dta
cap erase world_shape_coord.dta
shp2dta using "ne_110m_admin_0_countries.shp", database(world_shape) ///
coordinates(world_shape_coord) genid(id)
//Source: http://www.naturalearthdata.com/downloads/110m-cultural-vectors/

*Correct iso_a2
use  world_shape, clear
drop if iso_a2=="-99"

merge 1:1 iso_a2 using data, keep(1 3) nogen
// 注意作者未提供原始数据 data,因此运行会报错
// 后续出现的 jobs_scarce_code 是 data 中的一个变量

* ---------------------------
* 3. 绘制地图
* ---------------------------
spmap jobs_scarce_code using world_shape_coord if admin!="Antarctica", id(id) ///
  fcolor(Reds) osize(.1) ocolor(black) ///
  clmethod(custom)  clbreaks(0 .2 .40 .6 .8 1)  ///
  legend(position(8) ///
  region(lcolor(black)) ///
  label(1 "No data") ///
  label(2 "0% to 20%") ///
  label(3 "20% to 40%") ///
  label(4 "40% to 60%") ///
  label(5 "60% to 80%") ///
  label(6 "80% to 100%")) ///
  legend(region(color(white))) ///
  plotregion(icolor(bluishgray)) ///
  title("When jobs are scarce, men should have more of a right to a job than women.") ///
  subtitle("Agreement with the statement above by country") ///
  note("Source: World Values Survey (2014 or last available year)") ///
  saving(map, replace)

  graph export map.png, as(png)  replace

绘制的图如下:

语法要点:

7. 断点回归图 (RD plots)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/RD plots

7.1 附加置信区间的 RD 图

* Regression Discontinuity plots with confidence interval

* 1. 加载数据
use "RD plots\Regression discontinuity plots with confidence intervals\data.dta", clear

* 2. 计算断点
sum cutoff
local cutoff = r(mean)

* 3. 绘图
twoway  ///
 (lpolyci tmt_status pmt_score if pmt_score < `cutoff', clcolor(navy) acolor(gs14)) || ///
 (lpolyci tmt_status pmt_score if pmt_score > `cutoff', clcolor(navy) acolor(gs14)), ///
 xline(`cutoff', lcolor(red) lwidth(vthin) lpattern(dash)) ///
 ytitle(Probability of receiving treatment) ///
 xtitle(Proxy means test score) ///
 legend(off) ///
 bgcolor (white) graphregion(color(white))  ///
 note("Note: gray area is 95% confidence interval.")

* 4. 输出图片
gr export "figure.png", width(5000) replace

绘制的图如下:

语法要点:

  • lpolyci 绘制局部多项式回归拟合的置信区间;
  • lpoly 绘制局部多项式回归拟合的曲线。

8. 散点图 (Scatter plots)

该小节的代码和数据来自 Stata-IE-Visual-Library/Library/Scatter plots

8.1 附加线性回归拟合线和置信区间的散点图

*Figure: Scatter plot with fitted line and confidence interval

* 1. 加载数据
use "Scatter plots\Scatter plot with fitted line and confidence interval\data.dta", clear

* 2. 画图Graph
twoway ///
  (lfitci jobs_scarce_code avg_growth ) ///
  (scatter jobs_scarce_code avg_growth ///
     if continent == "Africa", mcolor(cranberry) m(O) )  ///
  (scatter jobs_scarce_code avg_growth ///
     if continent == "Asia",   mcolor(dkgreen) m(D) ) ///
  (scatter jobs_scarce_code avg_growth ///
     if continent == "Europe", mcolor(ebblue) m(T) ) ///
  (scatter jobs_scarce_code avg_growth ///
     if continent == "North America", mcolor(dkorange) m(O)) ///
  (scatter jobs_scarce_code avg_growth ///
     if continent == "Oceania", mcolor(navy) m(D) ) ///
  (scatter jobs_scarce_code avg_growth ///
    if continent == "South America", mcolor(red) m(T)),  ///
  xlabel(-5(5)15) 		///
  xtitle("Average Annual GDP per Capita Growth Rate (%)", axis(1)) ///
  ylabel(0(0.2)1) ///
  ytitle("Gender Value Indicator" ) ///
  legend(order( 3 4 5 6 7 8) ///
        label(3 "Africa") label(4 "Asia")  ///
        label(5 "Europe") label(6 "North America") ///
        label(7 "Oceania") label(8 "South America")    ///
  ring(0) position(4)) ///
  title("Gender Value Indicator and GDP per Capita Growth" "Correlation")  ///
  note("Source: World Values Survey (2014 or last available year) and World Bank") ///
  graphregion(color(white)) bgcolor(white)

* 3. 保存图片
graph export "figure.png", as(png)  replace

绘制的图如下:

语法要点:

  • scatter 命令中的 m(...) 选项设置散点的形状;
  • 因为 lfitci 命令会同时绘制置信区间阴影和拟合线,所以 legend 命令中的数字从 3 开始。

8.2 附加多项式回归拟合线和置信区间的散点图

* Figure: Scatter plot with polynomial smoothing and confidence interval

**************************************
***	          Notes            ***
**************************************
/*
需要下载外部命令 grc1leg,步骤如下:
1. 输入 findit grc1leg
2. 选择并点击 http://www.stata.com/users/vwiggins
3. 点击下载 (click here to install)

grc1leg:用于合并图像,使其共用一个图例
*/
findit grc1leg


***加载数据
use "Scatter plots\Scatter plot with polynomial smoothing and confidence intervals\data", clear

***画第一个图
sum cons_pae_m_sine, det

twoway scatter cons_pae_sd_sine cons_pae_m_sine if cons_pae_m_sine < `r(p99)' ///
	|| lpolyci cons_pae_sd_sine cons_pae_m_sine if cons_pae_m_sine < `r(p99)', ///
	legend(off) ///
	xtitle(" " "`=ustrunescape("\u006D\u0302")'", size(large)) ///
	ytitle("`=ustrunescape("\u0073\u0302")'" " ", size(large)) ///
	xlabel(50 "50" 100 "100" 150 "150" 200 "200") ///
	graphregion(color(white)) bgcolor(white) ///
	name(s_by_mhat)

***画第二个图
sum cons_pae_m_sine, det

twoway scatter cv cons_pae_m_sine ///
         if cons_pae_m_sine<`r(p99)' & cons_pae_m_sine>`r(p1)' ///
	|| lpolyci cv cons_pae_m_sine ///
	     if cons_pae_m_sine<`r(p99)' & cons_pae_m_sine>`r(p1)', ///
	mcolor(maroon) ///
	ytitle("`=ustrunescape("\u0073\u0302/\u006D\u0302")'" " ", size(large)) ///
	xtitle(" " "`=ustrunescape("\u006D\u0302")'", size(large)) ///
	legend(order(2 3) label(3 "Local Poly.") label(2 "95% CI")) ///
	graphregion(color(white)) bgcolor(white) ///
	name(cv_by_mhat)

***合并两个图
grc1leg s_by_mhat cv_by_mhat, ///
	row(1) legendfrom(cv_by_mhat) ///
	imargin(0 0 0 0) graphregion(margin(t=0 b=0)) ///
	position(6) fysize(75) fxsize(150) ///
	graphregion(color(white)) plotregion(color(white))

***输出图片
graph export "figure.png", as(png) replace

绘制的图如下:

语法要点:

  • grc1leg 为外部命令,用于合并图像,使其共用一个图例;
    • 本例中 legendfrom(cv_by_mhat) 声明用 cv_by_mhat 这张图的图例。
  • ustrunescape 函数是对 Unicode 转义字符的解码;
    • `=ustrunescape("\u0073\u0302/\u006D\u0302")' 输出效果为 s^/m^
    • `=ustrunescape("\u006D\u0302")' 输出效果为 m^
    • `=ustrunescape("\u0073\u0302")' 输出效果为 s^
    • 趣用请参考用“emoji”秀出你的风采 这篇文章。

9. 总结

本推文较为详细地介绍了 11 个 Stata 案例,希望能为图形的美化提供一定的启发。

注:本推文相关数据,do file 及资料获取方式如下:

  1. 百度云盘:https://pan.baidu.com/s/1eROYRAoBMA9697VMRRrCkA, 提取码: o1mz
  2. 项目主页:https://gitee.com/arlionn/Stata-IE-Visual-Library,进入后,点击右上角的【Fork】按钮,可以把这个项目完整复制到你的码云账号下,随时查看。亦可单击【克隆/下载】按钮,将项目代码下载到本地。

10. 相关推文

相关课程

连享会-直播课 上线了!
http://lianxh.duanshu.com

免费公开课:


课程一览

支持回看

专题 嘉宾 直播/回看视频
最新专题 文本分析、机器学习、效率专题、生存分析等
研究设计 连玉君 我的特斯拉-实证研究设计-幻灯片-
面板模型 连玉君 动态面板模型-幻灯片-
面板模型 连玉君 直击面板数据模型 [免费公开课,2小时]

Note: 部分课程的资料,PPT 等可以前往 连享会-直播课 主页查看,下载。


关于我们

  • Stata连享会 由中山大学连玉君老师团队创办,定期分享实证分析经验。直播间 有很多视频课程,可以随时观看。
  • 连享会-主页知乎专栏,400+ 推文,实证分析不再抓狂。
  • 公众号关键词搜索/回复 功能已经上线。大家可以在公众号左下角点击键盘图标,输入简要关键词,以便快速呈现历史推文,获取工具软件和数据下载。常见关键词:课程, 直播, 视频, 客服, 模型设定, 研究设计, stata, plus, 绘图, 编程, 面板, 论文重现, 可视化, RDD, DID, PSM, 合成控制法

连享会主页  lianxh.cn
连享会主页 lianxh.cn

连享会小程序:扫一扫,看推文,看视频……

扫码加入连享会微信群,提问交流更方便

✏ 连享会学习群-常见问题解答汇总:
https://gitee.com/arlionn/WD

New! lianxh 命令发布了:
随时搜索连享会推文、Stata 资源,安装命令如下:
. ssc install lianxh
使用详情参见帮助文件 (有惊喜):
. help lianxh