Stata8图形示例及代码

http://stat.smmu.edu.cn/FIELD/statagrh.htm

一、带标注的散点图
sysuse lifeexp, clear
keep if region==2 | region==3
replace gnppc = gnppc / 1000
label var gnppc "GNP per capita (thousands of dollars)"
gen lgnp = log(gnp)
qui reg lexp lgnp
predict hat 
label var hat "Linear prediction"
replace country = "Trinidad" if country=="Trinidad and Tobago"
replace country = "Para" if country == "Paraguay"
gen pos = 3 
replace pos = 9 if lexp > hat 
replace pos = 3 if country == "Colombia"
replace pos = 3 if country == "Para"
replace pos = 3 if country == "Trinidad"
replace pos = 9 if country == "United States"

#delimit ;

twoway
(scatter lexp gnppc, mlabel(country) mlabv(pos))
(line hat gnppc, sort)
, xsca(log) xlabel(.5 5 10 15 20 25 30, grid) legend(off) 
  title("Life expectancy vs. GNP per capita") 
  subtitle("North, Central, and South America") 
  note("Data source:  World bank, 1998") 
  ytitle("Life expectancy at birth (years)")
;
#delimit cr

二、对数坐标散点图
sysuse lifeexp, clear
gen gnp000 = gnppc/1000
label var gnp000 "GNP per capita, thousands of dollars"
scatter lexp gnp000, xsca(log) ///
xlabel(.5 2.5 10(10)40, grid)

三、加权散点图
sysuse census, clear
gen drate = divorce / pop18p 
label var drate "Divorce rate"
scatter drate medage [w=pop18p] if state!="Nevada", msymbol(Oh) ///
  note("State data excluding Nevada" ///
       "Area of symbol proportional to state's population aged 18+")

四、带置信区间的直线回归图
sysuse auto, clear
quietly regress mpg weight 
predict hat
predict stf, stdf
gen lo = hat - 1.96*stf
gen hi = hat + 1.96*stf
scatter mpg weight || line hat lo hi weight, pstyle(p2 p3 p3) sort

五、期望寿命折线图
sysuse uslifeexp, clear
gen diff = le_wm - le_bm 
label var diff "Difference"

#delimit ;
line le_wm year, yaxis(1 2) xaxis(1 2) 
  || line le_bm year 
  || line diff  year
  || lfit diff  year
  ||, 
  ylabel(0(5)20, axis(2) gmin angle(horizontal))
  ylabel(0 20(10)80,     gmax angle(horizontal))
  ytitle("", axis(2))
  xlabel(1918, axis(2)) xtitle("", axis(2))
  ytitle("Life expectancy at birth (years)")
  title("White and black life expectancy")
  subtitle("USA, 1900-1999")
  note("Source: National Vital Statistics, Vol 50, No. 6" 
       "(1918 dip caused by 1918 Influenza Pandemic)")
  legend(label(1 "White males") label(2 "Black males"))
  legend(col(1) pos(3))
  ;
#delimit cr

六、带置信区间的散点图
sysuse auto, clear 
quietly regress mpg weight 
predict hat
predict s, stdf
gen low = hat - 1.96*s
gen hi  = hat + 1.96*s
#delimit ;

twoway
rarea low hi weight, sort bcolor(gs14) ||
scatter  mpg weight
;
#delimit cr

七、折线、散点复合图
sysuse sp500, clear
#delimit ;
twoway 
line close date, yaxis(1)
||
bar change date, yaxis(2)
||
in 1/52, 
ysca(axis(1) r(1000 1400)) ylab(1200(50)1400, axis(1))
ysca(axis(2) r(-50 300)) ylab(-50 0 50, axis(2)) 
ytick(-50(25)50, axis(2) grid)
legend(off)
title("S&P 500")
subtitle("January - March 2001")
note("Source:  Yahoo!Finance and Commodity Systems, Inc.")
yline(1150, axis(1) lstyle(foreground))
;
#delimit cr

八、人口金字塔
sysuse pop2000, clear
replace maletotal = -maletotal/1e+6
replace femtotal = femtotal/1e+6
gen zero = 0
#delimit ;

twoway 
bar maletotal agegrp, horizontal xvarlab(Males)
||
   bar  femtotal agegrp, horizontal xvarlab(Females)
||
   sc  agegrp zero     , mlabel(agegrp) mlabcolor(black) msymbol(i)
||
, 
xtitle("Population in millions") ytitle("")
plotregion(style(none))
ysca(noline) ylabel(none)
xsca(noline titlegap(-3.5))
xlabel(-12 "12" -10 "10" -8 "8" -6 "6" -4 "4" 4(2)12 , tlength(0) 
grid gmin gmax)
legend(label(1 Males) label(2 Females)) legend(order(1 2))
title("US Male and Female Population by Age, 2000")
note("Source:  U.S. Census Bureau, Census 2000, Tables 1, 2 and 3")
;
#delimit cr

九、折线穗式图
sysuse sp500, clear
#delimit ;
twoway line close date, yaxis(1) || spike change date, yaxis(2) ||,
  yscale(axis(1) r(700  1400)) ylabel(1000(100)1400, axis(1))
  yscale(axis(2) r(-50 300))   ylabel(-50 0 50, axis(2)) 
  ytick(-50(25)50, axis(2) grid)
  legend(off)
  title("S&P 500")
  subtitle("January - December 2001")
  note("Source:  Yahoo!Finance and Commodity Systems, Inc.")
  yline(950, axis(1) lstyle(foreground))
  ;
#delimit cr

十、针式图
sysuse lifeexp, clear 
keep if region==3
gen lngnp = ln(gnppc)
quietly regress le lngnp 
predict r, resid 
twoway dropline r gnp, ///
  yline(0, lstyle(foreground)) mlabel(country) mlabpos(9) ///
  ylab(-6(1)6) ///
  subtitle("Regression of life expectancy on ln(gnp)" "Residuals:" " ", pos(11)) ///
  note("Residuals in years; positive values indicate" "longer than predicted life expectancy")

十一、直方图
sysuse sp500, clear 
#delimit ;

histogram volume, freq
  xaxis(1 2)
  ylabel(0(10)60, grid) 
  xlabel(12321 "mean" 
        9735 "-1 s.d." 
       14907 "+1 s.d." 
        7149 "-2 s.d."
       17493 "+2 s.d." 
       20078 "+3 s.d."
       22664 "+4 s.d.", axis(2) grid gmax)
  xtitle("", axis(2))
  subtitle("S&P 500, January 2001 - December 2001")
  note("Source:  Yahoo!Finance and Commodity Systems, Inc.")
  ;
#delimit cr

十二、带拟合分布曲线的直方图
sysuse sp500, clear 
#delimit ;

histogram volume, freq normal
xaxis(1 2)
ylabel(0(10)60, grid) 
xlabel(12321 "mean" 
      9735 "-1 s.d." 
     14907 "+1 s.d." 
      7149 "-2 s.d."
     17493 "+2 s.d." 
     20078 "+3 s.d."
     22664 "+4 s.d."
, axis(2) grid gmax)
xtitle("", axis(2))
subtitle("S&P 500, January 2001 - December 2001")
note("Source:  Yahoo!Finance and Commodity Systems, Inc.")
;
#delimit cr

十三、折线穗式条形复合图
sysuse sp500, clear 
replace volume = volume/1000
#delimit ;

twoway
rspike hi low date ||
line   close  date ||
bar    volume date, barw(.25) yaxis(2) ||
in 1/57
, ysca(axis(1) r(900 1400))
  ysca(axis(2) r(  9   45))
  ylabel(, axis(2) grid)
ytitle("                          Price -- High, Low, Close")
ytitle(" Volume (millions)", axis(2) bexpand just(left))
legend(off)
subtitle("S&P 500", margin(b+2.5))
note("Source:  Yahoo!Finance and Commodity Systems, Inc.")
;
#delimit cr

十四、区间图
sysuse sp500, clear 
gen month = month(date)
sort month
by month: egen lo = min(volume)
by month: egen hi = max(volume)
format lo hi %10.0gc
by month: keep if _n==_N
#delimit ;

twoway rcap lo hi month, 
  xlabel(1 "J"  2 "F"  3 "M"  4 "A"  5 "M"  6 "J" 
                 7 "J"  8 "A"  9 "S" 10 "O" 11 "N" 12 "D")
  xtitle("Month of 2001")
  ytitle("High and Low Volume")
  yaxis(1 2) ylabel(12321 "12,321 (mean)", axis(2) angle(0))
  ytitle("", axis(2))
  yline(12321, lstyle(foreground))
  msize(*2)
  title("Volume of the S&P 500", margin(b+2.5))
  note("Source:  Yahoo!Finance and Commodity Systems Inc.")
;
#delimit cr

十五、区域图
sysuse gnp96, clear 
#delimit ;

twoway area d.gnp96 date, xlabel(36(8)164, angle(90)) 
  ylabel(-100(50)200, angle(0))
  ytitle("Billions of 1996 Dollars")
  xtitle("")
  subtitle("Change in U.S. GNP", position(11))
  note("Source: U.S. Department of Commerce, Bureau of Economic Analysis")
  ;
#delimit cr

十六、根据函数制作的曲线图
#delimit ;
twoway function y=exp(-x/6)*sin(x), range(0 12.57)
  yline(0, lstyle(foreground))
  xlabel(0 3.14 "pi" 6.28 "2 pi" 9.42 "3 pi" 12.57 "4 pi")
  plotregion(style(none))
  xscale(noline)
;
#delimit cr

十七、正态曲线下的面积图
#delimit ;

twoway 
  function y=normden(x), range(-4 -1.96) bcolor(gs12) recast(area) || 
  function y=normden(x), range(1.96 4) bcolor(gs12) recast(area) ||
  function y=normden(x), range(-4 4) clstyle(foreground) ||, 
  plotregion(style(none))
  yscale(off) xscale(noline)
  legend(off)
  xlabel(-4 "-4 sd" -3 "-3 sd" -2 "-2 sd" -1 "-1 sd" 0 "mean" 
  1 "1 sd"   2 "2 sd"   3 "3 sd"   4 "4 sd", grid gmin gmax)
  xtitle("")
  ;
#delimit cr

十八、期望寿命曲线图
sysuse uslifeexp, clear

#delimit ;

twoway line  le year || fpfit le year ||,
  ytitle("Life Expectancy, years")
  xlabel(1900 1918 1940(20)2000)
  title("Life Expectancy at Birth")
  subtitle("U.S., 1900-1999")
  note("Source:  National Vital Statistics Report, Vol. 50 No. 6")
  legend(off)
  text(48.5 1923 
     "The 1918 Influenza Pandemic was the worst epidemic"
     "known in the U.S."
     "More citizens died than in all combat deaths of the"
     "20th century.", box place(se) just(left) margin(l+4 t+1 b+1) width(85))
  ;
#delimit cr

十九、矩阵图
sysuse lifeexp, clear
gen lgnppc = ln(gnppc)
gr matrix popgr lexp lgnp safe

二十、半对角矩阵图
sysuse lifeexp, clear
generate lgnppc = ln(gnppc)
graph matrix popgr lgnp safe lexp, half

二十一、带网格线的矩阵图
sysuse lifeexp, clear
generate lgnppc = ln(gnppc)
graph matrix popgr lgnp safe lexp, maxes(ylab(#4, grid) xlab(#4, grid))

二十二、带上标题、标注、网格线的矩阵图
sysuse lifeexp, clear
generate lgnppc = ln(gnppc)
label var lgnppc "ln GNP per capita"
#delimit ;
graph matrix popgr lgnp safe lexp, 
  maxes(ylab(#4, grid) xlab(#4, grid))
  subtitle("Summary of 1998 life-expectancy data")
  note("Source:  The World Bank Group")
  ;
#delimit cr

二十三、横向组合折线图
sysuse uslifeexp, clear 
line le_male   year, saving(male)
line le_female year, saving(female)
graph combine male.gph female.gph, ycommon 

二十四、纵向组合折线图
sysuse uslifeexp, clear 
line le_male   year, ylab(,grid) saving(male)
line le_female year, ylab(,grid) saving(female)
gr combine male.gph female.gph, col(1) scale(1)

二十五、复合矩阵图
sysuse lifeexp, clear 
gen loggnp = log10(gnppc)
label var loggnp "Log base 10 of GNP per capita"

#delimit ;

scatter lexp loggnp, yscale(alt) xscale(alt) xlabel(, grid gmax) saving(yx)

twoway histogram lexp, fraction xscale(alt reverse) horiz saving(hy)

twoway histogram loggnp, fraction yscale(alt reverse) 
  ylabel(,nogrid) xlabel(,grid gmax) saving(hx)
  ;

graph combine hy.gph yx.gph hx.gph, hole(3) 
  imargin(0 0 0 0) graphregion(margin(l=22 r=22))
  title("Life expectancy at birth vs. GNP per capita")
  note("Source:  1998 data from The World Bank Group")
  ;
#delimit cr

二十六、面积不等的复合矩阵图
sysuse lifeexp, clear 
gen loggnp = log10(gnppc)
label var loggnp "Log base 10 of GNP per capita"

#delimit ;
scatter lexp loggnp, yscale(alt) xscale(alt) xlabel(, grid gmax) saving(yx)

twoway histogram lexp, fraction xscale(alt reverse) horiz fxsize(25) saving(hy)

twoway histogram loggnp, fraction
  yscale(alt reverse) ylabel(0(.1).2, nogrid)
  xlabel(,grid gmax) fysize(25)
  saving(hx) ;

graph combine hy.gph yx.gph hx.gph, hole(3) 
  imargin(0 0 0 0) graphregion(margin(l=22 r=22))
  title("Life expectancy at birth vs. GNP per capita")
  note("Source:  1998 data from The World Bank Group") ;
#delimit cr

二十七、生存曲线
sysuse cancer, clear
stset studytime, fail(died)
streg, distribution(exponential)
predict S, surv
sts graph, plot(line S _t, sort)

二十八、复式条图
sysuse citytemp, clear 
#delimit ;
graph bar tempjuly tempjan, over(region) bargap(-30)
  legend( label(1 "July") label(2 "January") )
  ytitle("Degrees Fahrenheit")
  title("Average July and January temperatures")
  subtitle("by regions of the United States")
  note("Source:  U.S. Census Bureau, U.S. Dept. of Commerce") ;
#delimit cr

二十九、带标注的复式条图
sysuse citytemp, clear 
#delimit ;
graph bar tempjuly tempjan, over(region) bargap(-30)
  legend( label(1 "July") label(2 "January") )
  ytitle("Degrees Fahrenheit")
  title("Average July and January temperatures")
  subtitle("by regions of the United States")
  note("Source:  U.S. Census Bureau, U.S. Dept. of Commerce")
  blabel(bar, position(inside) format(%9.1f) color(white)) ;
#delimit cr

三十、分组复式条图
sysuse citytemp, clear 
#delimit ;
graph bar (mean) tempjuly tempjan, 
  over(division, label(labsize(*.75)))
  over(region)
  bargap(-30) nofill
  ytitle("Degrees Fahrenheit")
  legend( label(1 "July") label(2 "January") )
  title("Average July and January temperatures")
  subtitle("by region and division of the United States")
  note("Source:  U.S. Census Bureau, U.S. Dept. of Commerce") ;
#delimit cr

三十一、水平分组复式条图
sysuse citytemp, clear 
#delimit ;
graph hbar tempjan, over(division) over(region) nofill
  ytitle("Degrees Fahrenheit")
  title("Average January temperature")
  subtitle("by region and division of the United States")
  note("Source:  U.S. Census Bureau, U.S. Dept. of Commerce") ;
#delimit cr

三十二、分组复式条图
sysuse nlsw88, clear
#delimit ;
graph bar wage, over(smsa, descend gap(-30)) over(married) 
  over(collgrad, relabel(1 "Not college graduate" 2 "College graduate"))
  ytitle("")
  title("Average Hourly Wage, 1988, Women Aged 34-46")
  subtitle("by College Graduation, Marital Status, and SMSA residence")
  note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics") ;
#delimit cr

三十三、水平堆积条图
sysuse educ99gdp, clear
generate total = private + public
#delimit ;
graph hbar (asis) public private, 
  over(country, sort(total) descending) stack
  title("Spending on tertiary education as % of GDP, 1999",
  span pos(11))
  subtitle(" ")
  note("Source: OECD, Education at a Glance 2002", span) ;
#delimit cr

三十四、水平条图
sysuse nlsw88, clear
#delimit ;
graph hbar wage, over(ind, sort(1)) over(collgrad)
  title("Average hourly wage, 1988, women aged 34-46", span)
  subtitle(" ")
  note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span)
  ysize(7) ;
#delimit cr

三十五、带标注的横向组合条图
sysuse nlsw88, clear
#delimit ;
graph hbar wage, over( occ, axis(off) sort(1) )
  blabel( group, pos(base) color(bg) )
  ytitle( "" )
  by( union, 
    title("Average Hourly Wage, 1988, Women Aged 34-46")
    note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics") ) ;
#delimit cr

三十六、带参考线的分类散点图
sysuse nlsw88, clear
#delimit ;
graph dot wage, over(occ, sort(1)) 
  ytitle("")
  title("Average hourly wage, 1988, women aged 34-46", span)
  subtitle(" ")
  note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span) ;
#delimit cr

三十七、带参考线的分类散点图
sysuse nlsw88, clear
#delimit ;
graph dot (p10) p10=wage (p90) p90=wage, 
  over(occ, sort(2)) 
  legend(label(1 "10th percentile") label(2 "90th percentile"))
  title("10th and 90th percentiles of hourly wage", span)
  subtitle("Women aged 34-46, 1988" " ", span)
  note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span) ;
#delimit cr

三十八、带参考线横向组合的分类散点图
sysuse nlsw88, clear
#delimit ;
graph dot wage, 
  over(occ, sort(1))
  by(collgrad, 
    title("Average hourly wage, 1988, women aged 34-46", span)
    subtitle(" ")
    note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span) );
#delimit cr

三十九、箱式图(须髯图)
sysuse bplong, clear
#delimit ;
graph box bp, 
  over(when) over(sex)
  ytitle("Systolic blood pressure")
  title("Response to treatment, by Sex")
  subtitle("(120 Preoperative Patients)" " ")
  note("Source:  Fictional Drug Trial, Stata Corporation, 2003") ;
#delimit cr

四十、水平箱式图(须髯图)
sysuse nlsw88, clear
#delimit ;
graph hbox wage, 
  over(ind, sort(1)) nooutside
  ytitle("")
  title("Hourly wage, 1988, woman aged 34-46", span)
  subtitle(" ")
  note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span) ;
#delimit cr

四十一、横向组合水平箱式图(须髯图)
sysuse nlsw88, clear
#delimit ;
graph hbox wage, 
  over(ind, sort(1)) nooutside
  ytitle("")
  by(union,
    title("Hourly wage, 1988, woman aged 34-46", span)
    subtitle(" ")
    note("Source:  1988 data from NLS, U.S. Dept. of Labor, Bureau of Labor Statistics", span) );
#delimit cr

.

   
 
原文地址:https://www.cnblogs.com/jungsee/p/8484128.html