Stata绘图技巧总结(五)

Stata绘图技巧总结(五)

本文是旧笔记的汇总,本文汇总了Stata绘图中的一些技巧。

连接点

Stata
1
2
vguse spjanfeb2001, clear
tw connected close tradeday, sort

Stata
1
tw connected close tradeday, connect(J) sort

Stata
1
tw connected close tradeday, connect(stepstair) sort

Stata
1
tw connected close dom, sort

Stata
1
tw connected close dom, sort(tradeday)

  • connect(L): 只连接dom增加的点
    Stata
    1
    tw connected close dom, sort(tradeday) connect(L)

蜡烛图

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
clear
input ///
str3 share str20 time price
abc "1/5/2011:10:34" 10.34
abc "1/5/2011:10:35" 10.25
abc "1/5/2011:10:36" 10.15
abc "1/5/2011:10:37" 10.73
abc "1/5/2011:10:39" 10.95
abc "1/5/2011:10:41" 10.53
abc "1/5/2011:10:45" 10.99
abc "1/5/2011:10:49" 11.05
abc "2/5/2011:10:34" 9.34
abc "2/5/2011:10:35" 9.25
abc "2/5/2011:10:36" 9.15
abc "2/5/2011:10:37" 9.73
abc "2/5/2011:10:39" 9.95
abc "2/5/2011:10:41" 9.53
abc "2/5/2011:10:45" 9.99
abc "2/5/2011:10:49" 9.05
abc "3/5/2011:10:34" 8.34
abc "3/5/2011:10:35" 8.25
abc "3/5/2011:10:36" 8.15
abc "3/5/2011:10:37" 8.73
abc "3/5/2011:10:39" 8.95
abc "3/5/2011:10:41" 8.53
abc "3/5/2011:10:45" 8.99
abc "3/5/2011:10:49" 12.05
abc "4/5/2011:10:34" 12.34
abc "4/5/2011:10:35" 12.25
abc "4/5/2011:10:36" 12.15
abc "4/5/2011:10:37" 12.73
abc "4/5/2011:10:39" 12.95
abc "4/5/2011:10:41" 12.53
abc "4/5/2011:10:45" 12.99
abc "4/5/2011:10:49" 17.05
end
gen double date = dofc(clock(time, "DMY hm"))
format date %tdCY-N-D
collapse (p1) p1 = price (p25) p25 = price ///
(p50) p50 = price (p75) p75 = price ///
(p99) p99 = price, by(date)

gen uav = p75-1.5*(p25-p75)
gen lav = p75+1.5*(p25-p75)
gen col = 2
replace col = (p50-p50[_n-1])>0 if _n != 1 //生成涨跌的虚拟变量
tw ///
rbar p75 p25 date if col == 0, barw(0.6) color(red) || ///
rbar p75 p25 date if col == 1, barw(0.6) color(green) || ///
rbar p75 p25 date if col == 2, barw(0.6) color(black) || ///
rspike uav lav date if col == 2, lw(thick) color(black) || ///
rspike uav lav date if col == 1, lw(thick) color(green) || ///
rspike uav lav date if col == 0, lw(thick) color(red) ///
leg(off) yla(, nogrid angle(0)) scheme(s1mono) xti(日期) yti(股价) note(绿涨红跌)

控制坐标轴

添加轴标题前后缀

Stata
1
2
3
vguse allstates, clear

tw sc ownhome propval100, yti("1990 Census Data", suffix) xti("In 1990 dollars", prefix)

Stata
1
tw sc rent700 ownhome || sc propval100 ownhome, yaxis(2)||, yti("Percent rents over $700", axis(1)) yti("Percent homes over $100,000", axis(2)) leg(pos(6) r(1))

添加小标签

Stata
1
tw sc propval100 faminc, ymlabel(10(20)90)

Stata
1
tw sc propval100 faminc, xla(minmax) yla(none)

添加杠杠

Stata
1
tw sc propval100 faminc, ytick(10(10)90)

Stata
1
tw sc propval100 faminc, ymtick(10(10)90)

Stata
1
tw sc propval100 faminc, ymtick(##10)

Stata
1
tw sc propval100 faminc, yla(#10, noticks)

Stata
1
tw sc propval100 faminc, yla(, nolabel)

Stata
1
tw sc propval100 region, xla(, valuelabel)

Stata
1
tw sc propval100 region, xla(1 "NorthEast" 2 "NorthCenter" 3 "Southern" 4 "Western")

Stata
1
tw sc propval100 faminc, yla(0(5)90, labsize(vsmall))

Stata
1
tw sc propval100 faminc, yla(, labgap(large))

Stata
1
tw sc propval100 faminc, yla(, tlength(large) tlwidth(thick) tpos(crossing))

Stata
1
tw sc propval100 faminc, ytick(#10, tpos(outside)) ymtick(#5, tpos(inside))

Stata
1
tw sc propval100 faminc, yla(, grid glw(vthin) glc(gs10) glp(shortdash))

Stata
1
tw sc propval100 faminc, yla(0(20)100, grid glc(gs8) glp(solid)) ymla(10(20)90, grid glc(gs11) glp(shortdash))

控制轴的尺度

Stata
1
2
vguse sp2001, clear
tw rspike high low tradeday, xsc(alt)

Stata
1
tw rspike high low tradeday, xsc(reverse)

使用对数坐标轴

Stata
1
tw rspike high low tradeday, xsc(log)

Stata
1
2
vguse allstates, clear
tw sc educ popden, xsc(log) xla(1 10 100 1000 10000)

Stata
1
2
vguse sp2001, clear
tw rspike high low tradeday, xsc(lw(thick)) sch(vg_s2m)

Stata
1
tw rspike high low tradeday, xsc(noline) sch(vg_s2m)

Stata
1
tw rspike high low tradeday, ysc(range(700 1400))

Stata
1
tw rspike high low tradeday || line volmil tradeday, sort yaxis(2) ||, ysc(range(700 1400) axis(1)) ysc(range(0 10) axis(2)) leg(pos(6) r(1)) yla(1000 1200 1400, axis(1)) yla(0 1 2, axis(2))

控制图例

Stata
1
2
3
4
5
vguse allstates, clear
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(- "Fitted" 2 "Lin. fit" 3 "Quad. fit" - "Observed" 1))

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(- "Fitted" 2 "Lin. fit" 3 "Quad. fit" - "Observed" 1) r(3) colfirst)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(- "Fitted" 2 "Lin. fit" 3 "Quad. fit" - "Observed" 1) r(3) holes(3) colfirst)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(2 "Linear" "Fit" 3 "Quadratic" "Fit") stack cols(1))

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(1 "% Own Home" 2 "Lin. fit" 3 "Quad. fit") r(1) pos(12) bexpand) sch(vg_rose)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(order(2 "Lin. fit" 3 "Quad. fit") r(1) pos(12) bexpand span) sch(vg_rose)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(size(large) color(maroon) fcolor(eggshell) box) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(region(fcolor(dimgray) lcolor(navy) lw(thick) margin(medium))) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(r(1) bmargin(t = 20)) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(symxsize(30) symysize(20)) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
leg(colgap(25) rowgap(20)) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
by(nsw, leg(at(4))) leg(cols(1)) sch(vg_s2c)

Stata
1
2
3
4
tw sc ownhome urban || ///
lfit ownhome urban || ///
qfit ownhome urban ||, ///
by(nsw, leg(pos(center) at(4))) leg(cols(1) size(large))

矩阵散点图

标签选项

Stata
1
vguse allstates, clear
Stata
1
gr matrix propval100 ownhome borninstate, ms(Sh)

Stata
1
gr matrix propval100 ownhome borninstate

Stata
1
2
vguse citytemp, clear
gr matrix heatdd cooldd tempjan tempjuly, ms(p)

Stata
1
2
vguse allstates, clear
gr matrix propval100 ownhome borninstate, ms(vlarge)

Stata
1
gr matrix propval100 ownhome borninstate, ms(*2)

Stata
1
gr matrix propval100 ownhome borninstate, msize(vlarge) mc(gs13)

Stata
1
gr matrix propval100 ownhome borninstate, msize(vlarge) mfc(gs13) mlc(black)

Stata
1
gr matrix propval100 ownhome borninstate, mlab(stateab)

Stata
1
gr matrix propval100 ownhome borninstate, mlab(stateab) mlabsize(vlarge)

控制坐标轴

Stata
1
2
3
4
5
6
7
gr matrix urban propval100 borninstate, ///
xla(20(10)100, axis(1)) ///
yla(20(20)100, axis(1)) ///
xla(0(15)100, axis(2)) ///
yla(0(20)100, axis(2)) ///
xla(10(30)100, axis(3)) ///
yla(15(15)100, axis(3))

控制全局轴

Stata
1
2
3
gr matrix urban propval100 borninstate, ///
maxes(xlabel(0(20)100) ylabel(0(20)100)) ///
xla(0(15)100, axis(2)) yla(0(15)100, axis(2))

tick

Stata
1
2
3
gr matrix urban propval100 borninstate, ///
maxes(xla(0(20)100) yla(0(20)100)) ///
xtick(0(10)100) ytick(0(10)100)

diagonal

Stata
1
2
gr matrix urban propval100 borninstate, ///
diagonal("% Urban" "% Homes over $100K" "% Born in State", fc(eggshell))

jitter:增加扰动,减少遮盖

Stata
1
gr matrix urban propval100 borninstate, jitter(3)

scale

Stata
1
gr matrix urban propval100 borninstate, scale(1.5)

by()

Stata
1
gr matrix urban propval100 borninstate, by(north)

Stata
1
gr matrix propval100 borninstate, by(north, compact)

Stata
1
2
3
gr matrix propval100 borninstate, ///
by(north, compact scale(*1.3)) ///
maxes(yla(, nolabels noticks))

交错条形图

Stata
1
2
3
4
5
6
7
8
9
sysuse citytemp, clear
gr bar tempjuly tempjan, over(region) ///
bargap(-30) leg(label(1 "July") ///
label(2 "January")) ///
yti("Degrees Fahrenheit") ///
ti("Averge July and January temperatures") ///
subti("by regions of the United States") ///
note("Source: US. Census Bureau, U.S. Dept. of Commerce") ///
blabel(bar, pos(inside) format(%9.1f) color(white))

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
generate No=_n
collapse (sum) N, by(region)
list

local i1=1

forvalues i=1/`=_N'{
gr_edit plotregion1.barlabels[`i1'].text = {}
gr_edit plotregion1.barlabels[`i1'].text.Arrpush N=`=No[`i']'
local ++i1

gr_edit plotregion1.barlabels[`i1'].text = {}
gr_edit plotregion1.barlabels[`i1'].text.Arrpush N=`=No[`i']'
local ++i1
}

将两个柱状图叠放到一张图上

Stata
1
2
3
use "http://stats.idre.ucla.edu/stat/data/hsbdemo", clear
grss twoway hist math if female == 1, start(30) width(5) ///
|| hist math if female == 0, start(30) width(5)

Stata
1
2
3
grss twoway hist math if female == 1, start(30) width(5) ///
color(red) || hist math if female == 0, start(30) width(5) ///
, legend(order(1 "Female" 2 "Male"))

Stata
1
2
3
grss twoway hist math if female == 1, start(30) width(5) ///
color(red) || hist math if female == 0, start(30) width(5) color(none) ///
, legend(order(1 "Female" 2 "Male"))

  • 使用fcolor设置柱状图内部的填充色,lcolor设置柱状图的边框颜色
Stata
1
2
3
twoway hist math if female == 1, start(30) width(5) color(red) ///
|| hist math if female == 0, start(30) width(5) fcolor(none) ///
lcolor(black) legend(order(1 "Female" 2 "Male"))

几率比

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sysuse nlsw88, clear
logit union married never_married collgrad south

parmest, norestore eform
egen axis = axis(estimate), label(parm)

tw ///
sc axis estimate, ///
xline(1) yla(, valuelabel ang(0)) msize(small) || ///
rcap min95 max95 axis, horiz ///
leg(order(1 "point estimate" ///
2 "95% conf. int." ///
) pos(6)) ///
xti("odds ratio") yti("")

gr export "几率比.png", replace

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sysuse nlsw88, clear
logit union married never_married collgrad south

parmest, norestore eform

tab estimate, gen(kk)

gen a = _n

egen axis = axis(a estimate), label(parm)
tw bar estimate axis, base(1) horiz ///
barw(0.5) xline(1) yla(, valuelabel ang(0)) || ///
rcap min95 max95 axis, horiz leg( ///
order(1 "point estimate" ///
2 "95% conf. int." ///
) pos(6)) ///
xti("odds ratio") yti("")

脊柱图

Stata
1
2
sysuse auto, clear
spineplot foreign rep78, sch(burd4)

Stata
1
spineplot rep78 foreign, sch(vg_brite)

Stata
1
2
3
set scheme vg_rose
bysort foreign rep78: gen freq = _N
spineplot foreign rep78, text(freq, mlabsize(*1.4)) bar1(color(gs14)) bar2(color(gs10))

Stata
1
spineplot foreign rep78, text(freq, mlabsize(*1.4)) bar1(color(gs14)) bar2(color(gs10)) legend(off) yla(0.1 "Domestic" 0.9 "Foreign", noticks axis(1))

三维图形绘制

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// 命令安装:
// ssc install surface, replace
// ssc install scat3, replace

// 随机生成用于画图的数据
clear
set obs 600
gen x = int((_n-mod(_n-1,30)-1)/30)
gen y = mod(_n-1,30)
gen z = normalden(x,10,3)*normalden(y,15,5)*10000

// surface命令的语法:
// surface [var1 var2 var3][,options twoway_options]
grss clear
grss surface x y z
// 调整大小,设置主题
grss surface x y z, nowire scale(0.8) sch(s1color)
// 增加坐标轴表签、图形题目等等
grss surface x y z, ylabel(0 13 20 29) labelround(1) xtitle(X) ztitle(Z) ytitle(Y) title(3Dplot) nowire sch(sj) scale(0.8)

// scat3命令的语法:
/* scat3 xvar yvar zvar [if exp][in range][,rotate(#) elevate(#) axistype(axis_type) axes(line_options)
shadow[(scatter_options)] spikes(rspike_options)
titlex([title_text][,maker_label_options])
titley([title_text][,marker_label_options])
titlez([title_text][,marker_label_options])
varnames separate(varname) graph_options]
*/
scat3 x y z, sch(economist) scale(0.29) titlez(, mlabang(0) mlabs(vhuge)) titlex(, mlabs(vhuge)) titley(,mlabs(vhuge))
scat3 x y z, rot(45) elev(45) titlez(Z, mlabang(0) mlabpos(0) mlabs(vhuge)) titlex(X, mlabpos(7) mlabs(vhuge)) titley(Y, mlabpos(7) mlabs(vhuge)) title("myplot", size(tenth) pos(12)) sch(economist) scale(0.3333)
//rot()、elev():分别用来指定旋转角度、仰角角度,默认都是45度;常用的视觉效果较好的组合为:30-60、45-45、60-30

散点图&条件分布图

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sysuse auto, clear
keep if foreign
sort weight
reg mpg weight
predict fit
predict se, stdp
* stdp: calculate standard error of the prediction.

tw ///
sc mpg weight, pstyle(p3) ms(o) || ///
function weight[3] - 1000 * normalden(x, `=fit[3]', `=se[3]'), range(`=fit[3]-5' `=fit[3]+5') horiz pstyle(p1) || ///
function `=fit[3]', range(`=weight[3]' `=weight[3] - 1000*normalden(0, se[3])') pstyle(p1) || ///
function weight[17] - 1000 * normalden(x, `=fit[17]', `=se[17]'), range(`=fit[17]-5' `=fit[17]+5') horiz pstyle(p1) || ///
function `=fit[17]', range(`=weight[17]' `=weight[17] - 1000*normalden(0, se[17])') pstyle(p1) || ///
function weight[21] - 1000 * normalden(x, `=fit[21]', `=se[21]'), range(`=fit[21]-5' `=fit[21]+5') horiz pstyle(p1) || ///
function `=fit[21]', range(`=weight[21]' `=weight[21] - 1000*normalden(0, se[21])') pstyle(p1) || ///
line fit weight, clwidth(*2) leg(off) yti("每加仑汽油/英里数") xti(重量) ti("带回归线和置信区间密度的散点图", size(4.8) margin(t = 0 b = 1.5) span) caption("graph46", box size(vsmall) pos(5) ring(10)) yla(, nogrid ang(0)) scheme(s1mono)

生成预测值与绘制预测结果

Stata
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
sysuse auto, clear
reg price c.mpg##c.weight##c.weight i.foreign
qui sum mpg
local m = r(mean)
local sd = r(sd)

preserve
replace foreign = 0
replace mpg = `m'
predict yhatm

replace mpg = `m' - `sd'
predict yhatl

replace mpg = `m' - 2*`sd'
predict yhatll

replace mpg = `m' + `sd'
predict yhath

replace mpg = `m' + 2*`sd'
predict yhathh

format yhat* %8.0gc

sort weight
tw line yhatll yhatl yhatm yhath yhathh weight, ///
title("Predicted price for US cars") ///
yti("Predicted price (US {c S|})") ///
lp(solid solid solid solid solid) ///
lc("255 255 204" ///
"161 218 180" ///
" 65 182 196" ///
" 44 127 184" ///
" 37 52 148") ///
leg(order( - "mpg" ///
1 "mean - 2*sd" ///
2 "mean - 1*sd" ///
3 "mean" ///
4 "mean + 1*sd" ///
5 "mean + 2*sd")) ///
sch(vg_rose)
restore

回归拟合与样条

Stata
1
2
3
vguse allstates.dta, clear
tw sc ownhome pcturban80 || ///
lfit ownhome pcturban80

pcycle():使线条的颜色与散点的颜色相同

Stata
1
2
tw sc ownhome pcturban80 || ///
lfit ownhome pcturban80 ||, pcycle(1)

更多拟合方法

Stata
1
2
3
4
5
6
7
8
tw sc ownhome pcturban80, msize(small) || ///
lfit ownhome pcturban80 || ///
qfit ownhome pcturban80 || ///
mspline ownhome pcturban80 || ///
fpfit ownhome pcturban80 || ///
lowess ownhome pcturban80 || ///
mband ownhome pcturban80 || ///
lpoly ownhome pcturban80

lpoly的选项:degree(2):二次拟合

Stata
1
2
tw sc ownhome pcturban80, msize(small) || ///
lpoly ownhome pcturban80, degree(2)

置信区间:默认使用stdp:CIs from SE of prediction; the default

Stata
1
2
tw lfitci ownhome pcturban80 || ///
sc ownhome pcturban80, msize(small)

把两个图层的顺序换一下:

Stata
1
2
tw sc ownhome pcturban80, msize(small) || ///
lfitci ownhome pcturban80

lfitci的选项:stdf:CIs from SE of forecast

Stata
1
2
tw lfitci ownhome pcturban80, stdf || ///
sc ownhome pcturban80, msize(small)

90%置信区间:

Stata
1
2
tw lfitci ownhome pcturban80, level(90) || ///
sc ownhome pcturban80, msize(small)

不绘制拟合线:

Stata
1
2
tw lfitci ownhome pcturban80, nofit || ///
sc ownhome pcturban80, msize(small)

改变线条的颜色、粗细:

Stata
1
2
tw lfitci ownhome pcturban80, lp(dash) lw(thick) || ///
sc ownhome pcturban80, msize(small)

改变置信区间的颜色

Stata
1
2
tw lfitci ownhome pcturban80, bcolor(stone) || ///
sc ownhome pcturban80, msize(small) sch(vg_brite)

把置信区间用线条显示:默认为ciplot(rarea)

Stata
1
2
tw lfitci ownhome pcturban80, ciplot(rline)|| ///
sc ownhome pcturban80, msize(small)

更改置信区间线条的颜色、粗细:

Stata
1
2
tw lfitci ownhome pcturban80, ciplot(rline) lp(dash) lw(thick) lcolor(green*0.8) || ///
sc ownhome pcturban80, msize(small)

其他拟合

Stata
1
2
tw qfitci ownhome pcturban80 || ///
sc ownhome pcturban80, msize(small) sch(vg_brite)

Stata
1
2
tw lpolyci ownhome pcturban80 || ///
sc ownhome pcturban80, msize(small) sch(vg_brite)


# Stata

评论

程振兴

程振兴 @czxa.top
截止今天,我已经在本博客上写了636.8k个字了!

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×