Tuesday 27 February 2018

Stata marginsplot binary options


여백을 사용하여 회귀 결과 탐색. 회귀 분석을 실행하면 다음 결과는 결과의 의미를 파악하는 것입니다. 여백 명령은 모델을 이해하기위한 강력한 도구이며이 기사에서는이를 사용하는 방법을 보여줍니다. 섹션 1과 섹션 2는 연구원 용 통계 섹션에서 직접 가져온 것입니다. 여기서는 마진 사용에 대한 정보를 찾는 사람들을 위해 여기에서 재현됩니다. 해당 자료에 익숙하다면 3.OLS 회귀 분석으로 건너 뛸 수 있습니다 비선형 용어를 사용하면 marginins 명령은 회귀 분석을 실행 한 후에 만 ​​사용할 수 있으며 가장 최근 회귀 명령의 결과에 적용됩니다. 첫 번째 예제에서는 Stata와 함께 제공되는 자동 데이터 집합을로드하고 다음 회귀를 실행합니다. sysuse 자동 reg 가격 mpg 변위. 결과 변수의 레벨. 당신이 단지 그것을 입력하면, Stata는 각 관찰에 대한 종속 변수의 예측 값을 계산합니다. t 암컷은 표준 오차, t - 통계 등과 함께 그 예측의 평균값을보고합니다. 마진 뒤에 범주 형 변수가 오면 Stata는 먼저 범주형 변수의 모든 수준을 식별합니다. 그런 다음 각 값에 대해 평균 예측치를 계산합니다 종속 변수의 가치는 모든 관측치가 범주 형 변수에 대한 값을 가졌을 때입니다. 다른 모든 변수는 변경되지 않습니다. 따라서 모든 차량이 국내에 있었지만 여전히 기존 중량, 변위 등이있는 경우 평균 가격은 얼마입니까? 그런 다음 모든 자동차가 외국 일 경우 평균 가격은 얼마입니까? rep78의 다섯 가지 값 모두에 대해 동일하지만 그래픽 프레젠테이션을위한 후보가 너무 많기 때문에 marginsplot 명령은 이전의 margins 명령을 실행하고 그래프로 변환합니다. 연속 변수의 경우 여백은 분명히 모든 가능한 값을 볼 수는 없지만 at 옵션을 사용하여 검사 할 값을 지정할 수 있습니다 무게를 2000에서 4000으로 설정합니다. 이 값은 2,000 파운드로 설정된 무게로 가격의 평균 예상 값을 계산 한 다음 4000 파운드로 다시 설정된 무게로 계산합니다. 시나리오로 각 값을 생각하면 위 시나리오는 매우 간단하지만 at 옵션에 여러 변수와 값을 나열하여 훨씬 더 복잡한 시나리오 마진 출력은 먼저 각 시나리오에 숫자를 할당 한 다음 결과를 숫자로 제공합니다. 값은 numlist를 사용하여 지정합니다. numlist는 varlist와 같은 숫자 목록입니다 변수 목록이며 varlist처럼 numlist를 정의하는 여러 가지 방법이 있습니다. 모두보기 위해 help numlist를 입력하십시오. 가장 간단한 방법은 위와 같이 원하는 숫자를 나열하는 것입니다. 또한 numlist를 by로 정의 할 수도 있습니다. 시작 간격 end. margins을 지정합니다. 1500 500 5000.이 값은 1500, 2000, 2500 등으로 설정된 가중치의 평균 예상 가격을 5000까지 계산합니다. 실제 가중치 범위는 1760에서 4840입니다. 다시 말하지만 이것은 좋은 후보입니다 공변량의 효과. 공변량의 한계 효과 또는 그 공변량에 대한 평균 예측 값의 미분을보고 싶다면 dydx 옵션을 사용하십시오. 이 간단한 경우 파생 값은 선형 모델의 경우 항상 해당되는 mpg에 대한 계수 그러나 모델에 가중치와 가중치 제곱이 모두 포함되므로 모델을 변경해야합니다. 두 변경 사실을 고려해야합니다. 이 경우는 특히 혼란스럽지 만 예외는 아니기 때문에 무게는 음수이지만 제곱에 대한 계수는 양수입니다. 따라서 주어진 차에 대한 체중 변화의 최종 효과는 시작 무게에 크게 좌우됩니다. 마진 명령을 통해 평균 효과를 쉽게 알 수 있습니다. 여백은 각 자동차의 중량과 관련하여 예상 가격의 수치 미분을 계산 한 다음 평균을 계산합니다. 이렇게하면 마진은 실제 데이터를 살펴 봅니다. 따라서 호드 변경의 영향을 고려합니다 1,760 파운드에서 시민의 무게뿐만 아니라 4,840에서 링컨 콘티넨탈을 변경하는 것은 체중의 제곱 기간이 이전보다 후자와 더 중요합니다. 그 다음 2 362865의 결과를 얻으려면 다른 모든 자동차와 함께 평균합니다. 무게가 추가 될 때마다 예상 평균 가격이 2 36만큼 증가합니다. 무게가 변할 때 무게 변화의 효과가 어떻게 변하는 지 확인하려면 at 옵션을 다시 사용하고 결과를 음모하십시오. 1500 500 5000 마진 플롯에 결과가 나타납니다. 우리는 약 2000 미만의 무게의 낮은 값을 위해, 실제로 무게를 늘리는 것이 자동차의 가격을 낮춘다. 하지만, 대부분의 자동차의 경우 중량 증가 가격을 지불해야한다. dydx 옵션은 이원 변수에도 적용된다. 그러나 외국인은 모델에 입력되었으므로 마진은 외국과 관련하여 파생물을 가져갈 수 없다는 것을 안다. 즉, 모든 자동차가 약간 더 외국화된 경우 일어날 일을 계산한다. 따라서 모든 자동차가있는 시나리오와 외국이고 모든 자동차가 국내에있는 시나리오 당신은 running. and 확인하여 자신을 뺄 수 있습니다. 이진 결과 모델 및 예측 확률. 마진 명령은 항상 비선형이기 때문에 이진 결과 모델을 사용하면 더욱 유용합니다. 자동 데이터 집합을 메모리에서 가져온 다음 SSCC 웹 사이트에서 대학원생을로드합니다. 이것은 1 만 명의 학생으로 구성된 허구의 데이터 집합입니다. 정확히 절반은 사회 경제적 지위가 높고 1 / 2은 정확히 아닙니다. 각 그룹의 절반 정도가 중재 또는 치료 치료는 졸업 확률을 높이기 위해 고안된 것입니다. 대학원 변수는 실제로 졸업했는지 여부를 알려줍니다. 목표는 치료에 차이가 있는지 여부 1을 결정하고, 치료의 효과가 사회 경제적 지위 SES와 다른지 여부를 결정하는 것입니다. 당신은 간단한 logit 모델로 첫 번째 질문에 답할 수 있습니다. 로그 치료는 highSES를 치료합니다. 치료에 대한 계수는 긍정적이고 중요합니다. 중재는 졸업 확률을 증가시켰다. highSES는 더욱 큰 영향을 미쳤음을 주목하라. 다음은 두 가지 사이의 상호 작용을 추가하여 효과가 SES에 의존하는지 여부를 검사한다. highSES 치료에 대한 계수는 0 그러나 그것은 치료가 SES에 관계없이 치료 효과가 정확히 동일하다는 것을 의미합니다. 바이너리 결과는 종종 교차비의 관점에서 해석되기 때문에, 이전 회귀를 옵션으로 반복하여 볼 수 있습니다. 고지를 치료하십시오. 이것은 우리에게 알려줍니다 당신이 치료를 받으면 졸업 할 확률은 SES와 상관없이 치료를받지 않으면 졸업 할 확률이 약 2 83 배입니다. 연구원은 때때로 확률 비율과 확률 비율을 혼동합니다. 즉, 처리됩니다. 올바르지 않습니다. 두 개의 범주 형 변수 사이의 상호 작용을 검사 할 여백을 묻는 경우, 해당 변수의 가능한 모든 조합에 대한 시나리오가 작성됩니다 변수 높은 SES 낮은 SES, 치료를하지 않은 4 가지 가능한 시나리오 모두에 대해 예상되는 졸업 확률을 쉽게 얻을 수 있습니다. 낮은 SES 학생의 경우 치료가 예상 졸업 확률을 약 49에서 약 73으로 높입니다. 높은 SES 학생의 경우, 치료는 눈금 확률을 96에서 98로 증가시킵니다. 이제 확률 비율을 계산하기위한 공식에 해당 확률을 연결하면 두 경우 모두 교차비 비율이 2 83 인 것으로 나타납니다. , 여기에 주어진 두 자리 근사는 아닙니다. 치료는 두 경우 모두에서 물류 기능을 통과하는 선형 함수에 동일한 양을 추가합니다. 그러나 물류 함수의 모양을 생각해보십시오. 치료는 높은 경우 졸업 확률에 미치는 영향이 훨씬 적습니다 SES 학생들은 자신의 확률이 이미 매우 높기 때문에 훨씬 더 높을 수는 없습니다 Low SES 학생들은 stee 슬로프가되는 물류 곡선의 일부입니다 따라서 선형 함수의 변화는 예측 된 확률에 훨씬 더 큰 영향을 미칩니다. 마진 명령은 가장 직접적으로 질문에 답할 수 있습니다. 처리의 효과는 SE에서 dydx와 at. margins의 조합으로 달라지며, dydx는 highSES에서 처리합니다. 0 1. 당신은 또한 마진 highSES, dydx로 이것을 할 수 있습니다. 다시 한번, 위에서 얻은 레벨을 빼서 얻은 것과 같은 숫자입니다. 항상 레벨을 바라 보면서 변화가 시작된 곳을 아는 것이 좋습니다. 무슨 일이 벌어지고 있는지 더 잘 이해할 수 있습니다. 마진에있는 사람, 즉 예상 확률이 0에 가까워지는 사람들에 대한 예상 확률을 변경하는 것이 가장 쉬운 일반적인 규칙입니다. 그러나 이것은 물류 기능의 속성이지 데이터 그것은 당신이 로짓 모델을 실행할 때 당신이 결정할 때 가정합니다. 다항로 짓. 다중 로짓 모델은 계수가 두 상태 만 비교하기 때문에 해석하기가 더 어려울 수 있습니다. d 다항식 로짓 결과 해석의 함정을 설명하기 위해 신중하게 작성된 다음 데이터 세트입니다 .1, 2 및 3 값과 연속 변수 x를 취하는 정수 y라는 두 변수를 포함합니다. 이들은 음의 상관 관계가 있습니다. cor y x 이제 다음 모델을 실행하십시오. 결과 2에 대한 x의 계수는 음수이므로 x가 증가하면 y가 2가 될 확률이 감소한다고 말하고 싶습니다. 하지만 실제로는 마진 명령을 사용하면 변수는 예상 결과를 예측합니다. 예측 옵션은 예상되는 결과 확률에 관심이 있다고 지정합니다. 2 실제로 결과 2의 확률은 파생 상품이 x 일 때 증가합니다. 0 016. 어떻게하면 mlogit에 의해 주어진 계수가 주어진 결과의 확률을 기본 결과와 비교한다는 것을 상기 할 수 있습니다. 결과 2에 대한 x 계수 -54는 x가 증가함에 따라 observa tions는 결과 2에서 결과 1로 이동합니다. 결과 x에 대한 -21 292의 x 계수는 x 증가로 관측 값이 결과 3에서 결과 1로 이동할 가능성이 있음을 나타냅니다. x가 증가하면 관측치는 결과 3에서 결과 2로 이동하며 실제로이 효과가 2에서 1로 이동하는 것을 지배합니다. 회귀의 기본 범주를 변경하면 관찰 할 수 있습니다. 음계, 기본 2. 이제 계수에 대해 알려줍니다. 결과 2와 비교 된 각 결과의 확률 및 결과 3에 대한 음의 x 계수가 절대 값에서 절대 값보다 훨씬 크다는 사실은 결과 1에 대한 양수 x 계수보다 x를 증가 시키면 결과 확률이 높아진다는 것을 의미합니다. 2. 마진 회귀 결과가 무엇인지 알아보기. 마지막 수정 2 14 2014.3 Stata Graphics. Stata는 그래프 명령을 통해 액세스 할 수있는 뛰어난 그래픽 기능을 제공합니다. 개요는 도움말 그래프를 참조하십시오. 통계의 가장 일반적인 그래프 s는 점 또는 선을 표시하는 XY 플롯입니다. twoway 부속 명령을 통해 Stata에서 사용할 수 있으며, 31 개의 부속 부속 명령 또는 플롯 유형이 있습니다. 가장 중요한 것은 분산 및 행입니다. 또한 간단히 막대 그래프를 설명합니다. bar 서브 커맨드 및 다른 플롯 유형을 포함합니다. Stata 10은 그래프를 대화식으로 수정하는 데 사용할 수있는 그래픽 편집기를 도입했습니다. 그러나 연구의 모든 단계를 문서화하고 재현성을 보장하는 목표와 충돌하기 때문에이 연습을 권장하지 않습니다. .3 1 산포도. 이 절에서는 먼저 2 절에서 사용 된 출산 률 감소 데이터를 사용하는 몇 가지 그림을 설명 할 것입니다. 1 net-aware Stata 유형에서 데이터를 읽으십시오. 식욕을 자극하려면 여기에 생산할 음모를 작성하십시오. 이 부분에서. 3 1 1 간단한 산점도. 사교적 인 설정에 의해 출산율 변화의 단순한 산점도를 생성하려면 명령을 사용하십시오. 먼저 y를 지정하면, x Stata는 변수 레이블을 사용하여 축에 레이블을 붙입니다. ey이 정의되어 있지 않거나 그렇지 않은 경우 변수 이름입니다. 명령은 twoway scatter로 축약되거나 그래프에서 유일한 플롯 인 경우 그냥 분산 될 수 있습니다. 이제 몇 개의 종과 휘파람을 추가 할 것입니다. 3 1 2 Fitted Lines. fit 회귀선 또한 회귀 분석을 실행하고 피팅 된 선을 계산 한 다음 플롯을 작성해야하는 패키지가 있습니다. Stata는 lfit 플롯 유형을 사용하여 한 단계로 모든 작업을 수행 할 수 있습니다. 2 차 적합을위한 qfit 플롯도 있습니다. 괄호 안에 각 서브 플롯을 묶음으로써 산점도와 결합 할 수 있습니다. 하나는 가로 막대 두 개를 사용하여 플롯을 결합 할 수도 있지만, 괄호를 사용하는 방법은 클리어입니다. 이제 우리는 회귀선 주위에 신뢰 밴드를 넣고 싶다고 가정합니다. Stata는 신뢰 영역을 회색 밴드로 그리는 lfitci 플롯 유형 2 차핏에 대한 qfitci 밴드 신뢰 영역이 일부 지점을 가릴 수 있으므로 영역을 먼저 그립니다. 이 명령은 t 그는 y 축이지만 대신 legend를 사용합니다 ytitle 옵션을 사용하여 y 축에 대한 레이블을 지정할 수 있고 legend를 사용하여 오히려 분명한 전설을 생략 할 수 있습니다. 여기에서 twoway 명령의 옵션으로 두 가지를 지정합니다. 독자는 새로운 라인의 시작 부분에 쉼표를 붙였습니다. 3 1 3 포인트 지정하기. 포인트에 사용되는 마커를 제어 할 수있는 여러 가지 옵션이 있습니다 (모양과 색상, 도움말 마크로 시도 참조). mlabel varname 옵션을 사용하여 다른 변수에 포함 된 텍스트를 사용하여 포인트에 라벨을 지정합니다. 다음 단계에서는 국가 이름을 플롯에 추가합니다. 라벨에 약간의 문제는 코스타리카와 트리니다드 토바고의 중복이며, 니카라과 12 시간제를 사용하여 마커에 상대적인 레이블의 위치를 ​​지정함으로써이 문제를 해결할 수 있습니다. 12는 위, 3은 오른쪽, 6은 아래, 9는 왼쪽입니다. mlabv 옵션 변수에 의해 설정된 위치를 유지하는 변수 3시 방향을 기본으로 설정 한 다음 코스타리카를 9시 시계로, 트리니다드 토바고를 11시 시계 위로 조금 움직이면서 니카라과와 파나마를 조금 움직여 2시 시계로 움직일 수 있습니다. 그래프는 다음과 같습니다 .3 1 4 제목, 범례 및 자막. 제목, 레이블 및 범례를 포함한 모든 양방향 그래프에 적용되는 옵션이 있습니다. Stata 그래프에는 일반적으로 맨 위에 제목과 부제가 있고 일반적으로 범례 및 설명이 있습니다 더 자세한 내용을 보려면 help titleoptions를 입력하십시오. 일반적으로 제목 만 있으면됩니다. Stata 11에서는 그래프의 텍스트에 굵게, 기울임 꼴, 그리스 문자, 수학 기호 및 글꼴 선택을 포함 할 수 있습니다. 자세한 내용은 도움말 그래프 텍스트를 입력하십시오. 그래프에 대한 최종 조정은 선형 피팅과 95 신뢰 구간을 지정하는 범례를 추가하는 것이지만 불임 자체는 감소시키지 않습니다. 범례의 2 차 선형 맞춤 1 95 CI 옵션을 사용하여 두 번째 및 첫 번째 항목에 우리는 반지 0을 사용하여 그림 영역 내에서 범례를 움직입니다. , 그리고 pos 5를 사용하여 5 o 시계 위치 근처에 범례 상자를 놓습니다. 우리의 완전한 명령이 그 때입니다. 결과는이 섹션의 시작 부분에 표시된 그래프입니다. 그래프가 약간 다르게 보일 경우 우리는 내가 사용한 다른 색 구성표를 사용했기 때문일 것입니다 s2color의 사용자 정의 된 버전 구성표에 대한 자세한 내용은 아래 3 2 5를 참조하십시오. 3 1 5 축 스케일 및 레이블. xscale 및 yscale을 포함하여 축의 스케일링 및 범위를 제어하는 ​​옵션이 있으며 산술, 로그 또는 반전 될 수 있습니다 , 자세한 내용은 help axisscaleoptions를 입력하십시오. 다른 옵션은 xlabel xtick 및 xmtick과 같이 y 축에 대해서도 주 및 보조 눈금 및 레이블의 배치 및 레이블 지정을 제어합니다. 자세한 내용은 axislabeloptions 도움말을 참조하십시오. 일반적으로 기본값은 허용되지만 nice 당신이 그들을 바꿀 수 있다는 것을 알기 위해서. 3 2 라인 플롯. 미국의 기대 수명에 관한 데이터를 사용하여 라인 플롯을 설명하고, Stata와 함께 제공되는 데이터 세트 중 하나로서 사용 가능합니다. 사용 가능한 다른 것을보기 위해 시도하십시오. 20 세기에 걸쳐 백인과 흑인 남성에 대한 기대 수명 다시 한 번, 식욕을 자극하기 위해 최종 제품을 보여 드리겠습니다. 그런 다음 그래프를 비트 단위로 작성하겠습니다. 3 2 1 간단한 선 플롯. 가장 간단한 플롯이 사용합니다 모든 기본값. 1920 년 전에 딥으로 당황한 경우 Google 미국 평균 수명 1918 명령은 줄을 두 줄 또는 심지어 줄까지 줄 수 있습니다. 이 바로 가기는 산산이 및 선에서만 작동합니다. 당신은 하나 이상의 y 변수를 지정하기 위해 순서는 y 1 y 2 ymx입니다. 우리의 예에서는 흰색과 검은 색 수명에 해당하는 두 가지를 지정했습니다. 또는 두 개의 라인 플롯을 사용할 수있었습니다. 제목과 전설. 기본 그래프는 꽤 좋지만 전설은 너무 말쑥 해 보인다. 우리는 대부분의 정보를 제목으로 옮기고 전설 속에서만 민족성을 유지할 것이다. 여기에 세 가지 옵션이 사용된다. 보통 Stata에서 쉼표 제목 부제 및 전설 전설 선택 ion에는 여러 가지 하위 옵션이 있습니다. 첫 번째 줄은 흰색과 두 번째 검정을 나타냅니다. 키와 레이블을 나열하려면 목록에서 제외하는 키를 생략합니다. 일치하는 키가없는 텍스트를 추가하려면 하이픈 또는 키에 대한 빼기 기호 많은 다른 범례 옵션이 있습니다. 자세한 정보는 legendoption 도움말을 참조하십시오. 기대 수명을 향상시키는 5 o 시계 위치 주변의 말하기 영역 내에서 범례를 움직여 공간을 조금 더 활용하고 싶습니다. 여분의 방을 남겨 두었습니다. 앞에서 언급했듯이, 우리는 반지 0을 내부 원으로 사용하여 그림 영역을 옮길 수 있고 pos 5를 사용하여 5시 시계 위치 근처에 놓을 수 있습니다. 전설의 하위 옵션이므로 범례 안에 들어가야합니다. 3 2 3 선 스타일. 나는 당신에 대해 안다. 그러나 플롯의 기본 선을 구별하기가 어렵다. Stata는 선 스타일을 다른 방식으로 제어 할 수있다. clstyle 옵션을 사용하면 전경 그리드 yxline과 같은 명명 된 스타일을 사용할 수있다. 또는 사용 된 스타일에 대해 p1-p15 b y lines 1 ~ 15, help linestyle을 참조하십시오. 이것은 아래에서 설명하는 스키마에서 스타일 요소를 선택하려는 경우 유용합니다. 스타일의 세 가지 구성 요소를 선 패턴, 너비 및 색상으로 지정할 수 있습니다. 패턴이 지정됩니다 clpattern 옵션 사용하기 가장 일반적인 패턴은 단색 대시입니다. 자세한 내용은 라인 패턴 스타일 도움말을 참조하십시오. 라인 폭은 clwidth를 사용하여 지정합니다. 사용 가능한 옵션에는 얇은 중간 및 두께가 포함됩니다. 자세한 내용은 라인 폭 스타일을 참조하십시오. 색상은 clcolor 옵션을 사용하여 지정할 수 있습니다. 빨강 흰색 및 파랑 청록색 시엔나 및 기타 색상 값 또는 RGB 값과 같은 색상 이름은 도움말 색상 스타일을 참조하십시오. 흰색은 파란색을 지정하고 검정은 빨간색을 지정하는 방법은 여기에 나와 있습니다. clcolor는 선 음영의 옵션이므로, 괄호 라인 커맨드를 삽입하고 거기에 삽입합니다 .3 2 4 스케일 옵션. 이것은 수명의 향상이 세기 후반에 다소 둔화 된 것처럼 보입니다. 이것은 로그 스케일을 사용하여 더 잘 이해할 수 있습니다. 직선은 일정한 퍼센트 개선을 나타냅니다. 양방향 명령의 축 옵션을 사용하여 쉽게 수행 할 수 있습니다. 도움말 축 옵션을 참조하십시오. 특히 yscale을 사용하면 산술 로그 또는 역 스케일을 선택할 수 있습니다. 플로팅을 제어하는 ​​서브 옵션 범위 range 여기에서는 y - 범위를 25에서 80으로 지정하여 커브를 조금 위로 이동시킵니다. 3 2 5 Graph Schemes. Stata는 스키마의 모양을 제어하는 ​​스키마를 사용합니다 (도움말 스키마 참조). set schemename이있는 모든 그래프 그래프 표시, scheme schemename과 함께 다른 스키마를 사용하여 마지막 그래프를 다시 표시 할 수도 있습니다. 사용 가능한 스키마 목록을 보려면 graph query, schemes를 입력하십시오. 화면 그래프에는 s2color를, Stata 매뉴얼에는 s1manual을 사용하십시오. Economist에서 사용 된 스타일에 대한 경제학자를 사용합니다. 후자를 사용하여이 섹션의 시작 부분에 표시된 그래프를 얻습니다 .3 3 Graphs. Stata는 메모리에 저장되어있는 마지막 그래프를 추적합니다. 그것을 호출 할 때 그래프를 만들 때 이름 옵션을 사용하면 그래프에 여러 그래프를 실제로 유지할 수 있습니다. 그래프를 결합 할 때 유용합니다. 자세한 내용은 help graph combine를 입력하십시오. 그래프 자체를 저장하지 않는 한 데이터를 저장하더라도 Stata를 종료하십시오. Stata의 자체 포맷을 사용하여 현재 그래프를 디스크에 저장하려면 graph save filename을 입력하십시오. 이 명령에는 두 가지 옵션이 있습니다. 그래프를 현재 스타일을 포함하여 정지시키고 저장합니다. 기본값은 미래의 세션에서 편집 할 수있는 라이브 포맷으로 그래프를 저장하는 것입니다 (예 : 스키마 변경). Stata 포맷으로 그래프를 저장 한 후 명령 그래프 use filename을 사용하여 디스크에서로드하십시오. 그래프 저장 및 그래프 사용은 Stata 파일 저장 및 사용과 유사합니다. 메모리에 저장된 모든 그래프는 그래프 표시를 사용하여 표시 할 수 있습니다. 또한 목록 표시, 설명, 이름 바꾸기, 복사 또는 메모리에 저장된 그래프를 드롭하면 더 많은 것을 배우기 위해 help graphmanipulation을 입력하십시오. 다른 문서에 그래프를 통합하려는 경우 아마 더 이식성있는 형식으로 저장해야 할 것입니다. Stata의 명령 그래프 내보내기 파일명은 다양한 종류의 일반적으로 파일 확장자에서 이해할 수있는 벡터 또는 래스터 형식 Windows 메타 파일 wmf 또는 emf 또는 Adobe의 PostScript와 그 변형 ps, eps, pdf와 같은 벡터 형식은 기본적으로 드로잉 지침을 포함하므로 해상도 독립적이므로 포함하기에 가장 적합합니다. Portable Network Graphics png와 같은 래스터 형식은 현재 디스플레이 해상도를 사용하여 이미지를 픽셀 단위로 저장하며 웹 페이지에 포함시키는 것이 가장 좋습니다. 그래프 인쇄 또는 복사하여 붙여 넣기를 사용하여 그래프를 인쇄 할 수도 있습니다 Windows 클립 보드를 사용하여 그래프를 포함하는 창을 마우스 오른쪽 단추로 클릭 한 다음 컨텍스트 메뉴에서 복사를 선택하십시오 .2017 Germ n Rodr guez , Princeton University. 로지스틱 회귀 분석에서 여러 상호 작용을 이해하기 위해 marginins 명령을 어떻게 사용합니까? Stata 11 Stata FAQ. Stata 11에서 새로 추가 된 marginins 명령은 상호 작용을 이해하고 해석하는 데 매우 유용한 도구가 될 수 있습니다. 연속적인 상호 작용에 의한 범주 형 두 가지 로지스틱 회귀 모델 우리는 데이터 세트 mlogcatcon을로드함으로써 시작합니다. 이 데이터 세트에서 y는 이진 응답 변수이고 m과 s는 연속적 예측 변수입니다. 여성을 나타내는 변수 f는 이진 예측 자입니다. m과 s는 여기에 있습니다. 여기에 로지스틱 회귀 모형이 있습니다. f에 의한 상호 작용은 통계적으로 유의미하지만 m에 의한 상호 작용은 아닙니다. 이것은 비선형 모델이므로 모든 공변량의 값을 고려해야합니다. 모형에서 어떤 일이 일어나고 있는지 이해한다. 우리는 마진 명령으로 시작할 것이다. 마진 명령은 남녀 간의 확률 차이를 5 일 동안 관찰한다. m의 평균값에서 m을 유지하면서이 수준의 값을 얻습니다. 변수 m은 atmeans 옵션을 사용하여 평균값에서 유지됩니다. 위의 marginins 명령의 결과는 다음과 같습니다. 완벽하게 정확하면, m의 단일 값에 대한 확률의 개별 변화를 반영합니다. atmeans 옵션을 제거하면 우리는 평균 한계 효과를 얻습니다. 즉, m의 관측 값에 대해 평균 된 s의 각 값에 대한 확률의 이산 변화 마진 명령이 지금 어떻게 보이는지 알려드립니다. 95 신뢰 구간을 포함하여 이러한 결과를 그래프로 표시하십시오. Stata FAQ에 표시된 기술을 사용하여 필요한 값을 매트릭스에 배치하는 것으로 시작하겠습니다. 여백 명령의 결과를 그래프로 표시하는 방법은 무엇입니까? 행렬 명령 뒤에는 두 가지 선 그래프가옵니다. 위의 여백 명령과 그래프는 확률의 개별적인 변화가 diff를 통해 어떻게 변하는지를 잘 보여줍니다 그러나 s의 값은 다르지만 m 값이 다르면이 값이 어떻게 변하는 지 알지 못합니다. 마진 명령을 다시 한 번 시도해 봅니다. 이번에는 s와 m이 모두 변합니다. 처음 다섯 행은 5 개의 값에 대한 이산 변화를 나타냅니다. while 30에서 m을 잡고 다음 5는 40에서 m을 유지합니다. 그리고 계속해서 흥미로운 특징 중 하나는 전반적인 상호 작용이 중요 함에도 불구하고 이산 변화가 통계적으로 얼마나 중요한지입니다. 이제 우리는 필요한 값을 그래프의 준비에서 행렬을 사용합니다. 우선 s의 다른 값의 영향을 m의 각 값에 대한 별도의 선으로 그래프로 나타냅니다. 위의 여백 테이블에 중요한 값이 많지 않지만 m이 서로 다르게 보임 m = 30에 대한 선이 오히려 편평한 반면 m = 70에 대한 선은 처음으로 떨어지고 나서 등가의 등반 주위로 가파르게 등반하는 훨씬 더 많은 변동성을 보여줍니다. 이제 우리는 값에 대한 s의 차이 의 우리는 그래픽 명령 twoway 행의 변수를 반대로하여 s의 값에 대한 m의 차이점을 볼 수 있습니다. 물론, 우리는 이전의 그래프와 동일한 25 개의 값을보고 다르게 구성되었습니다. 이번에는 line 70 %가 다른 모델들보다 두드러진 모델입니다. 모델이이 모델보다 더 복잡하다면, 각 공변량에 대해 어떻게해야할지 결정해야합니다. 하나 이상의 값으로 일정하게 유지하거나 당신이 선택하는 것은 무엇이든, 공변량의 모든 값이 비선형 모델에서 중요하다는 것을 깨달을 필요가 있습니다. 이 3 단계 프로세스를 시도해 볼 수 있습니다. 1 레이스 2에 대한 재정 보조를 회귀 할 수 있습니다. 여백이있는 예측 된 값을 얻습니다. 3 막대를 만듭니다. 그래프는 marginsplot을 사용합니다. 재정 지원은 레이스 전에 i - 점을 사용하여 레이스가 정렬되지 않은 범주 형 변수임을 Stata에 알려줍니다. 마진, 레이스 마진 플롯, x 레이스 리사이클 막대. 확실합니다. twoway로이 작업을 수행하려면 bar 당신이 사용한 코드를 게시하면 도움이 될 것입니다. 재정적 지원을받는 사람들의 비율에 대한 간단한 요약 그림을 얻는 데 조금 복잡해 보이 긴하지만 감사합니다. 지금 사용하고있는 코드는. histogram FinancialAid, Race 별 불연속 퍼센트. 이 코드는 거의 내가 원하는 것입니다. 단, Race도 0을 표시하고 각 값의 정확한 백분율을 표시하지 않습니다. 비율을 추측 해 봐야합니다. 문서화 됨 blabel option. 당신은 당신의 변수가 0-1이라고 말했습니다. 어떤 경우에 그 평균은 그 간격에있을 것입니다. 어떻게 든 당신은 백분율을 가졌습니다. 그래서 당신이 원했던 것입니다. FinancialAid의 평균의 제목 퍼센트는 % 재정상의 도움이 필요합니다. 전설이 필요 없습니다. 카테고리가 축 레이블과 잘 어울립니다. 정확히 사용한 구문을 보여주는 것이 좋습니다. Nick Cox, 2014 년 4 월 28 일, 02 일 편집 14. 데이터를 표시하는 더 좋은 방법은 가로 막대 범례 텍스트가 abolishe 일 수 있습니다. d 독자는 범주의 정체성과 단일 수평 움직임으로 비율을 읽을 수 있습니다. 모든 막대가 동일한 것을 표시하고 개별 막대를 연결하는 데 더 이상 색상이 필요하지 않기 때문에 여러 종족마다 다른 색을 사용하지 않았습니다. 각 카테고리의 상대적인 크기를 표시하기 위해 차트의 세로 방향을 사용했습니다. 이것은 닉 코콕스 (Nick Cox)의 catplot 명령으로 수행되었습니다. 각 막대의 크기를 나타냅니다. catplot rvrace fw percent. An Stata Graphics. Stata 소개에는 게시 품질의 그래픽을 만들기위한 다양한 도구가 포함되어 있습니다. 만들 수있는 다양한 그래프와 제어 할 수있는 자세한 내용 사이 그래프, Stata 그래픽은 어려운 대상이 될 수 있습니다. 그러나 몇 가지 종류의 그래프 만 만들면됩니다. 대부분의 경우 Stata의 기본 설정은 괜찮습니다. Stata의 그래픽 사용자 인터페이스 GUI는 다양한 그래프 옵션을 직관적 인 방식으로 구성하여 각 그래프 구문을 암기하지 않고 필요할 때 찾을 수 있습니다. 그래프 명령을 작성한 후에는 그래프 명령을 파일에 두지 않아도되지만 의미는 없습니다 복잡한 그래프의 경우 GUI를 사용하여 저장할 명령을 작성할 수 있습니다. 상태 10에는 그래프를 작성한 후에 그래프를 수정할 수있는 그래프 편집기가 추가되어 그래프를 더욱 완벽하게 제어 할 수 있지만 GUI와는 다릅니다 그래프를 만들려면 편집기에서 나중에 다시 실행할 수있는 명령을 제공하지 않습니다. 나중에 데이터를 변경하면 처음부터 그래프를 시작해야합니다. 그러면 원하는 그래프를 만드는 것이 더 좋습니다 이 기사에서는 Stata GUI를 사용하여 그래프를 작성하는 방법, 세부 사항에 너무 많이 집착하지 않는 그래프 명령 구문의 구조, 일반적인 그래프 유형 및 그래프 편집기에 대해 논의합니다 연구원 또는 학생을위한 Stata로 시작하는 것을 고려하지 않으면 시작하기 전에 기본 Stata에 대해 어느 정도 익숙해야합니다. 이 기사를 사용하는 가장 좋은 방법은 컴퓨터에서 읽은 다음 설명 된 단계를 실제로 수행하는 것입니다. 기사는 Stata와 함께 제공되는 자동차 데이터 세트를 사용할 것이기 때문에 타이핑으로 시작하십시오. 로드하십시오. 특히 명백하게 드물게 사용되거나 드물게 사용되기 때문에 논의하지 않는 설정에서 자유롭게 실험 해보십시오. 데이터가 변경 될 수 있으므로 그래프가 쓸모 없거나 단순한 추악한 것으로 밝혀집니다. 그래픽 사용자 인터페이스를 사용하여 그래프를 작성하십시오. X 변수로 무게를, MPG로 간단한 산점도로 시작합니다. Y 변수 Stata는 Y 변수와 X 변수가있는 두 그래프를 의미하므로 그래픽 Twoway 그래프를 클릭합니다. 다음 단계는 플롯을 정의하는 것입니다. Stata 용어에서 플롯은 시각화 된 특정 데이터입니다 특정 방법으로, 예를 들어 무게에 대한 mpg의 산점도 그래프는 축, 제목, 범례 등을 포함한 전체 이미지입니다. 또한 하나의 그래프에 여러 개의 그림이 포함될 수 있습니다. 기본 twoway 대화 상자를 사용하면 그래프의 다른 특성을 제어 할 수 있습니다. 플롯을 정의하려면 [만들기]를 클릭하고 원하는 플롯을 설명 할 수있는 대화 상자를 엽니 다. 카테고리를 기본 플롯으로두고 유형을 분산 형으로 설정합니다. Y 변수를 선택하거나 mpg를 입력하고 X 변수를 선택하거나 입력하십시오. 참고 Linux Stata에서는 변수를 선택하여 변수의 이름을 입력 할 필요가 없습니다. Windows Stata에서 할 수도 있습니다. 제출을 클릭하면 그래프가 표시됩니다 created without closing the dialog box This allows you to look over the results and then easily make adjustments and try again Click Submit now and you should get a simple but professional looking scatter plot. Adding More Variables. If you want to add a second Y variable to the scatterplot, the easiest way is to type its name into the Y variable box after the one you ve already selected Stata does not allow you to select multiple variables from the list with the mouse, but it has no trouble understanding multiple variables in the Y variables box as long as you put them there yourself. To make a sensible graph with two Y variables without having multiple scales we need variables with similar values The trunk variable qualifies, so type it in the Y variable box after mpg and click Submit again. The result will be a scatter plot with both variables Note how Stata automatically puts the two variables in different colors and adds a legend explaining which is which The legend text is drawn from the variable labels, but you could override all these default behaviors if you so desired. Plotting a Subset of the Data. If you only want to include certain observations, you can specify which ones by clicking on the if in tab You can then type a condition in the If box, and on ly observations that meet the condition will be included in the plot Do not type the word if as that is assumed. To only plot foreign cars, type foreign in the If box. Recall that in Stata one is true and zero is false, and foreign is coded accordingly Thus if foreign is equivalent to if foreign 1 Click Submit and you ll get a much sparser graph. You can also use more complicated expressions For example, type foreign price 10000 and you ll get just the cars which are both foreign and cost less than 10,000 in 1978 dollars. Controlling the Markers. By default Stata marks each point with a small dot, but you can change this First click on the Plot tab again, and for best results set the Y variable back to just mpg Then click Marker Properties Set Symbol to Hollow circle Next check Add labels to markers and set the Variable to make then click Submit. As you see, each point is now a hollow circle with the name of the car printed next to it, but many of the names overlap You can improve the situat ion somewhat by changing Label angle to 45 degrees but in general you can only put useful labels on a scatter plot if it has a small number of observations and they re spread out. Overlaying Plots. Next we ll combine multiple plots Uncheck Add labels to markers Click Accept to accept these settings for Marker properties and go back to the Plot 1 window, then click Accept again to accept the plot as it is and go back to the main twoway window Click Create to add another plot to the graph This time we ll make a line plot Set the plot type to Line and again choose mpg and weight as the Y and X variables Click Submit to see the result. It s probably not what you expected--in fact it looks like a scribble That s because by default Stata draws the line from observation one to observation two to observation three and so forth What you want is a line from the observation with the lowest weight to the one with the next lowest weight, etc That s why Stata included the checkbox Sort on x variable Th is does not change the actual order of the observations in your data set, just the order in which they are connected in your line plot Check it and click Submit again This time you should get the graph you expected. Note that while the line connects all the points in the scatter plot, it goes to a lot of points that the scatter plot does not include That s because you didn t set an if condition for the line plot, so it s plotting all the observations in the data The ability to set different if conditions for different plots is very useful, though you ll note that the twoway window has its own if in tab which applies to all the plots. Line properties. You can control what the line looks like by clicking Line Properties The most commonly used option here is Pattern By default Stata distinguishes different line plots by color, but that doesn t help if the graph needs to be printed in black and white So instead you can set a pattern for each line Alternatively you can choose a scheme designed for printing To see it in action set Pattern to Dash Also try setting Connecting method to Stairstep. Plotting Subsamples. Let s go back to just plotting mpg vs weight but this time let s make the foreign cars one color and the domestic cars another You can do this by creating two plots, one for the foreign cars and one for the domestic cars, each having an if condition that limits it to the proper subpopulation Then Stata will make them different colors automatically. Begin by resetting everything Click Accept twice to get back to the main twoway window, then click the R button in the lower left to reset the plots Next click Create leave the type as Scatter set the Y variable to mpg and set the X variable to weight Then click if in and in the If box type foreign The exclamation mark is Stata for not so this means not foreign and is equivalent to foreign 0 Thus this plot will only include the domestic cars. Click Accept to get back to the main twoway window, then click Create again and re peat the entire process with one vital difference this time in the If box just type foreign This plot will include only the foreign cars Click Submit to see the result. The resulting graph very nicely makes the domestic cars blue and the foreign cars red However, the legend gives you no indication which is which To do that you ll need to take control of the legend yourself. Controlling the Appearance of a Graph. You haven t seen any options for controlling the legend, because thus far we ve been focused on the properties of individual plots The legend is not associated with a particular plot because it potentially contains information from all the plots Thus to get to it you need to click Accept and get back to the twoway window This is where you control aspects of the graph as a whole, including the legend. Click on the Legend tab The Legend behavior just controls whether the legend is shown or not Since Stata thinks our graph should have one and we agree, we can leave it set to Default O n the other hand, the default keys don t provide any useful information for this graph, so we need to override them Check Override default keys Then in the box below you need to type the number of each plot followed by how you want it to be labeled in quotation marks For this graph type.1 Domestic Cars 2 Foreign Cars. Now click Submit and you ll get a graph with a useful legend Note that the order in which you list the plots is the order in which they ll appear in the legend if you typed 2 Foreign Cars 1 Domestic Cars the legend would put the foreign cars first. The Organization Appearance button opens up a dialog box with all sorts of options relating to how the legend looks Click the Organization tab and set Rows Columns to Columns leaving it set to just one column. The Labels and Region tabs allow you to control the appearance of the legend text and the entire legend box respectively The various options like sizes and colors are self-explanatory, but these same options appear in many d ifferent contexts so it s worth taking a moment to experiment and see how they work Choose some different colors and such just to see how they work Then click Accept to get back to the main twoway window. The Placement button allows you to control where the legend is placed in the graph To understand how locations are specified, imagine putting the face of an analog clock over your graph 12 o clock is the top, 6 o clock the bottom, 3 o clock the right side, etc You can also specify that the legend goes inside the plot region rather than in the border area around it--just make sure it doesn t cover up anything important. Try setting the Position to 12 o clock and check Place legend inside plot region then click Submit to see the results. You can add a title to the legend using the Title tab of the in the Legend organization and appearance properties window, but you re much more likely to want to add a title to the graph itself To do so click Accept to get back to the main twoway window aga in, and then click on its Titles tab This gives you four boxes where you can put text the Title Subtitle Caption and Note The easiest way to see what each one means is to try them out, so type Title Subtitle Caption and Note in their respective boxes, and click Submit to see the result. As you see, Title and Subtitle go at the top, while Caption and Note go in the bottom left Each also has a particular font size associated with it However, these are simply defaults Click on the Properties button associated with each one and you can change its position and format Legend titles work in the same way, but they appear inside the legend box. If you want the text to be split across multiple lines, put each line in quotes To see this in action, replace Title with First Line Second Line and click Submit. Next we ll consider the axes of the graph Click on the Y axis tab the X axis tab is identical and the first thing you ll see is the Title box If a plot has just one Y variable, the default title f or the Y axis is that variable s label if it has one, or else simply its name If all the plots have multiple Y variables, the default is no title at all However, you can override the default by typing something here, and control its format by clicking Properties Type in Miles Per Gallon and click Submit to see the effect. Major ticks are the marks along the axis with numbers by them that we ve been seeing all along, but by clicking Major tick label properties you can control how many there are and where they are placed This is done by choosing one of several rules Use the default rule allows Stata to choose, which it usually does pretty well Suggest of ticks leaves most of the control to Stata but allows you to set roughly how many ticks there will be Min Max puts ticks at just the bottom and top of the axis Range Delta gives you complete control as long as you want the ticks to follow a regular rule For example, select Range Delta set the Minimum value to 0, the Maximum value to 40, an d the Delta to 5, then click Submit to see the results. The result is a Y axis that starts at zero and has ticks every five units, but note that the graph continues up to 41 because one car got 41 miles per gallon You can extend a graph by extending an axis remember the default version of this graph started at ten but you cannot truncate it Stata will always make the graph big enough to plot all the observations in your data If you really wanted the graph to stop at 40 you d have to add an if condition like mpg 40.Custom rules allow you to place ticks anywhere you like and have them say whatever you like The syntax is simply a list of numbers and associated labels For example, select Custom and in the Custom rule box type 10 Terrible 20 Mediocre 30 Very Good. The result is a less informative but more eloquent graph You could accomplish the same thing by putting value labels on the variable If you already have value labels assigned just click on the Labels tab and check Use value labels. E very tick does not need a text label For example, you could set the custom rule to 10 Terrible 15 20 Mediocre 25 30 Very Good 35 40 and get ticks every five units with labels at just 10, 20 and 30 However, this will cause the labels to overlap, or at least crowd each other To fix that, click on the Labels tab and set Angle to Horizontal Since this will force Stata to expand the margin to the left of the plot in order to make room for the labels, set the Size to v Small. However, the text labels don t include the numbers 10, 20 or 30, which looks odd since the other tick marks do have numbers To make those numbers appear, add them to the end of their respective text labels 10 Terrible 10 15 20 Mediocre 20 25 30 Very Good 30 35 40 That way they ll line up with the other numbers. Minor tick label properties controls smaller ticks that go in between major ticks They follow the same rules as major ticks, but the rules apply to the spaces between the major ticks rather than the whole axis Obvi ously the default size is smaller as well, but they are otherwise similar. Axis line properties controls the appearance of the axis itself, while Axis scale propertie s controls its scale This includes the ability to change it to a logarithmic scale, to reverse the scale, and to extend the scale but not to truncate it--see the discussion above. Using By with Graphs. Using by in a graph does not give you a completely separate graph for each subpopulation, but it does give you a separate plots within a single graph. The graph we have been working with has become unwieldy, so start by clicking the reset button Then set up a scatter plot of mpg on weight just like we have made before Click Accept to go back to the twoway window, then click on the By tab Check the box for Draw subgraphs for unique values of variables and in the Variables box type or select foreign. Click Submit and you ll see two scatter plots side-by-side, one for domestic cars and one for foreign cars. Now replace foreign with rep78 This variable takes on five values, plus it has some missing values Check the boxes for Add a graph with totals and Add graphs for missing values and click Submit. The resulting graph has seven plots one for each of the five standard values taken by rep78 one for observations which are missing rep78 and one for all observations However, the default arrangement of these plots is not particularly attractive, so click on Subgraph organization. One option would be to put all the plots on one row for easy comparison set Style to Compact, Rows Columns to Rows and then the number of rows to 1 Click Submit to see the result--obviously if you wanted to use this you d have to do something about the X axis labels, but you know how to do that. Another possibility would be to go back to the original format, but move the Total graph to the center of the bottom row First set the Style back to Default and Rows Columns back to Default and click Submit to take another look This arrangement has room f or nine plots in three rows with three plots each, and Stata numbers them left to right and then top to bottom The Total graph is currently in the seventh position If we tell Stata to leave the seventh position blank, it will automatically move to Total graph to the eighth position, which is in the center of the bottom row To do so, check Force holes in the placement of graphs and in the Holes box type 7 Note that you could put multiple numbers in this box if you wanted to leave multiple holes Click Submit to see the result. Now click Accept to get back to the twoway window The Subgraph titles and Subgraph regions are all about controlling appearance and are similar to what you ve seen before Subgraph axes are a little more interesting One problem with our last graph is that Stata tried to reduce clutter by only putting one set of axes per row and column, but given the layout it looks random You can fix that by clicking Subgraph axes and then under Show Axes set both Y axes and X axes t o Yes While you re here, also set Rescale axes to Yes for for both axes This tells Stata to choose the scale for each subgraph based on the points it contains rather than choosing one scale for all of them This makes each subgraph look nicer, but makes it impossible to compare them which may be the entire point of the graph. Overall Options. Finally click on the Overall tab to see some general-purpose options for the whole graph. Schemes are stored sets of defaults For example, the Economist scheme implements the graphics guidelines of the journal The Economist The two monochrome schemes s1 monochrome and s2 monochrome are particularly useful if you need to print your graph in black and white Feel free to experiment It s also possible to create your own schemes Try setting Scheme to s1 monochrome and then click Submit. Graph size can be confusing because when you re working with the graph in Stata, Stata will fit the graph in whatever size window you choose However, when it comes to printi ng or exporting the graph Stata will make it match the size you set here. Region properties refers to the Plot region everything inside a plot and the Graph region everything outside a plot This is where you can make global changes to the appearance of your graph like changing background colors. Saving a Graph. Once you ve created the graph you want, you can save it by clicking File Save As in the graph s window However, you should choose what type of file to save it as carefully The default, Stata Graph format has the advantage of allowing you to make further changes to the graph with the graph editor However gph files cannot be placed in other files like Word documents or web pages If you want to put your graph in a Word document use Enhanced Metafile format or for web pages we suggest Portable Network Graphics. Creating Graphs Using Commands. As you worked through the previous sections you ve probably noticed that Stata pasted a command into the Results window every time you created a gr aph Stata used everything you clicked on to formulate the command, but it s the command that actually created the graph As you can see, the commands to create graphs are often very complicated If you write the commands yourself you may be able to make them somewhat simpler, but not much. So why learn how to create graphs using commands at all First of all, for simple graphs it can be much faster For example, you can create your basic scatter plot of mpg on weight simply by typing. scatter mpg weight. Second, even if you ve created a graph using the graphical user interface you may want to modify it by recalling the command and making changes Third, there are a very few things that cannot be done using the graphical user interface. On the other hand, there s little point in trying to learn the proper syntax for every graph option Let the graphical user interface help you with details like choosing text sizes and colors What you need to know is the basic syntax structure, and that s what we ll discuss. No matter how you created your graph, you should store the command in a do file This allows you to recreate the graph later, if needed It also serves as a record of how you created the graph. Graph Commands. All graph commands really come down to one command graph It is followed by either a type of graph e g graph bar or a family of graphs followed by a type of graph e g graph twoway scatter Then comes whatever information is needed to create the graph itself However, the most common graph types and families were also made standalone commands, which is why you can just type scatter mpg weight. For the ubiquitous twoway family basically graphs with a Y axis and an X axis what follows is a varlist The last variable in the list is taken to be the X variable, and all the others are Y s--similar to how regress handles a varlist but in the opposite way. Graph commands can use if and in just like regular Stata commands they go at the end of the command but before any optionsbining Plot s. If you want to include multiple plots in a graph, they must be separated either by putting them in parentheses or by putting two pipe characters between them Thus to create a graph containing two scatter plots of mpg on weight one for foreign cars and one for domestic cars, you can type either. scatter mpg weight if foreign scatter mpg weight if foreign. twoway scatter mpg weight if foreign scatter mpg weight if foreign. Note how in the second case you had to start with twoway That s because a Stata command can t start with a parenthesis, but once you put it in the context of a twoway graph Stata will understand what you mean. Graph commands cannot use the standard by prefix, but most allow a by option that does the same thing. scatter mpg weight, by foreign. Graph options follow the general option rule of going at the end of the command following a comma, but by that definition a single graph can contain several commands For example, the Sort on x variable checkbox for line plots translat es into the sort option but it has to stay with the line plot if the graph has more than one Thus if you typed. line mpg weight scatter mpg weight, sort. the sort option would be applied to the scatter plot, where it would do little good Instead you should type. line mpg weight, sort scatter mpg weight. Things like titles are also options. scatter mpg weight, title MPG vs Weight. Note that the text of the title does not have to go in quotes--unless it has a comma in it You can use quotes to separate lines, just like when you typed it in the Title box. But what really makes life interesting is when your options have options Suppose you wanted the title to be merely medium large medlarge rather than the default very large vlarge , and also a dark red specifically, cranberry You can make it so with the size and color options, but to make it clear what they are controlling the size and color of they have to go inside the title s parentheses Yet they still follow a single comma Thus the command be comes. scatter mpg weight, title MPG vs Weight, size medlarge color cranberry. Of course it s at this point that it becomes attractive to let the graphical user interface keep track of the proper placement of such things for you, not to mention letting you know that medlarge and cranberry are among the available options. For the rest of this article we ll type out the graph commands rather than using the graphical user interface, partially for practice but mostly because we ll be making fairly simple graphs and that s the quickest way to do so. Other Types of Graphs. Stata can create dozens of different kinds of graphs--for a much larger sampling, see the Visual Overview on Stata s web site This section will discuss a few more that are fairly commonly used at the SSCC. Stata can plot several different kinds of fit lines automatically The most common are lfit linear fit , qfit quadratic fit , lfitci linear fit with confidence intervals and qfitci quadratic fit with confidence intervals They r e not very interesting by themselves--usually they re overlaid on a scatter plot The syntax is just like any other twoway graph Type. scatter mpg weight lfit mpg weight. Or if you prefer, set up the scatter plot in the graphical user interface as usual, then add a second plot setting the plot category and type to Fit plots and choosing Linear prediction --but typing it will be a whole lot faster. The versions that show confidence intervals need a little care because they can cover things up Try. scatter mpg weight qfitci mpg weight. Any points within the confidence interval are covered up by the shaded region You can fix that by reversing the order of the plots in the command However, qfitci is not one of the plot types that is recognized by itself, so you need to start with twoway. twoway qfitci mpg weight scatter mpg weight. Now all the points are shown Think of a Stata graph as a painting done with completely opaque paints If you have multiple plots each plot is a layer of paint, and layers that are added later cover up what was there before Thus plots that cover areas should be listed first, and anything that needs to go on top should be listed last. How ever, all these plots do is regress Y on X or Y on X and X 2 and plot the predicted values for Y If you want to run a more complicated regression there s no automatic command to plot the predicted values On the other hand, you can easily store the predicted values in a new variable and plot it. Suppose you wanted to plot the predicted probabilities you got from a logit of foreign on mpg a clear case of reversing cause and effect, but the methodology doesn t care No graph command will do this for you, but you can do it yourself. logit foreign mpg predict phat line phat mpg, sort. The result looks reasonable, but try it as a scatter plot. scatter phat mpg. This demonstrates that the only values of mpg represented in the graph are those represented in your data set and keep in mind many observations have the same value of mpg That may or may not be a problem, but if you wanted to plot a smooth curve over the full range of mpg you could replace the actual values of mpg with made-up numbers that are evenly distributed from 14 to 41.gen realMPG mpg replace mpg 41-14 n-1 N-1 14 predict phat2 scatter phat2 mpg replace mpg realMPG. Note that with multivariate regressions if you want to plot the effect of one variable you will probably need to set the others to their means before making predictions Otherwise the line will jump all over due to the effects of the other variables. Stata does two very different kinds of bar plots twoway bar is just a variation on what we ve seen before. twoway bar mpg weight. But there s also graph bar which is not part of the twoway family It plots summary statistics the default is mean rather than values, and is normally used to compare between variables or between groups Variables are simply listed, and the group variable is specified using the over option For example. graph bar weight price, over foreign. hbar is almost identical--it just turns everything sideways. graph hbar weight price, over foreign. If you want to compare something other than the mean, put that statistic in parentheses before the list of variables. graph hbar median weight price, over foreign. Histograms are very simple to create. Note that by default Stata does not put frequency on the Y axis, but probability density This fits with the idea of a histogram being an approximation to the probability density function, but probably isn t how you were taught to make histograms back in grade school You can have it plot frequencies using the frequency option percent is another that is frequently used. If you don t like Stata s default bins you can take control by either setting the number of bins bin option or the width of a bin width option You can get the same results either way The mpg variable goes from 12 to 41, for a total range of 29 Stata chose eight bins, which means each had a width of 29 8 3 625 If you wanted 10 bins, you could type. hist mpg, bin 10 frequency. But you ll get the exact same graph from. hist mpg, width 2 9 frequency. If you have discrete data, the discre te option tells Stata to choose bins accordingly For example, if you just type. Stata will choose eight bins even though rep78 only has five values The result is a confusing histogram of fairly simple data. However, if you add the discrete option Stata creates five bins for the five values. hist rep78, discrete. The result is a much clearer graph. Kernel Densities. You can overlay a kernel density on your histogram just by adding the kdensity option there s also a normal option to add a normal density. hist mpg, width 2 9 frequency kdensity. You can also create an independent kernel density plot with the kdensity command. The most commonly used option for kernel densities is bwidth which sets the bandwidth Compare. kdensity mpg, bwidth 5.kdensity mpg, bwidth 1.The Graph Editor. Stata includes a graph editor that can be used to modify a graph after it has been created Its big disadvantage is that it doesn t give you a command you can save in a do file and use to recreate the graph at will However, it does allow you to make changes very simply and easily. To see it in action, make a simple scatter plot. scatter mpg weight. Then click File Start Graph Editor You re now ready to make changes to this graph. On the left are several buttons that place the graph editor in a particular mode The top button, the arrow, puts it in pointer mode, which allows you to select an item on the graph to edit For example, if you click on the plot part of the graph i e inside the axes you ll be able to edit the plot region Color and Margin will appear in the tool bar at the top, but if you click More you ll be able to change many more properties. If you then click on a particular point you can change the plot itself Now the immediate options are Plottype Color Size and Symbol but you can again click More to see other things. As you do, note the Object Browser on the right Stata keeps track of the various parts of a graph in a sort of tree structure, and as you click on things it will highlight the object you ve selected You can also select an object directly For example, click title and you can add a title by typing it in the Text box Type in MPG vs Weight 1978 Cars and press Enter to see the results. The next three buttons the large T the diagonal line, and the circle with a plus sign allow you to add text, draw lines and place new points anywhere you need them As an example, let s add the Toyota Prius for comparison 46 mpg and about 3000 pounds for a 2008 four-door The smart way would be to add it to the dataset before making the graph, but we ll do it using the graph editor as an exercise. The first problem is that the graph ends at 42 mpg To fix that select yaxis1 in the Object Browser and click More Then set the Axis rule to Range Delta with a Minimum value of 10 a Maximum value of 50 and a Delta of 5 Click OK and the graph will be rescaled--and more ticks will be added so we have a better chance at marking 46 accurately. Now click the circle with a plus sign on the left and then cli ck as best you can at the location mpg 46 just above the line and weight 3000 This will create a hollow circle at that location by default, but note that you could change its appearance at will Seeing the point on the graph makes it clearer that the real advantage of a Prius over a 1978 VW Diesel the 1978 car with 41 MPG is not the Prius somewhat higher MPG, but the fact that it gets that MPG despite being a much heavier car. Now click on the T to add text and then click to the right of the new point This will give you the Textbox properties window In the Text box type 2008 Toyota Prius for comparison and set the Size to Small Then click OK. The bottom button on the left is the grid editor This allows you to make drastic changes to your graph, like rearranging the parts Use with discretion, and saving your graph before changing anything is highly recommended. This is a good time to mention why you might want to save graphs in Stata format while it s true that you can t put them into docum ents that way, you can make changes to them in the graph editor Thus you might want to keep two copies of important graphs, one in Stata graph format in case you need to make changes, and one in something like format that you can insert into your paper. Last Revised 6 7 2013.

No comments:

Post a Comment