Stata Marginsplot Binary Optionen


Exploring Regression Ergebnisse mit Margins. Once Sie ve eine Regression laufen, ist die nächste Herausforderung, um herauszufinden, was die Ergebnisse bedeuten Die Margins Befehl ist ein mächtiges Werkzeug für das Verständnis eines Modells, und dieser Artikel wird Ihnen zeigen, wie es zu verwenden Es enthält die folgenden Abschnitte. Sektionen 1 und 2 werden direkt aus dem Statistik-Bereich von Stata für Forscher, die sie hier zugunsten von denen, die speziell für Informationen über die Verwendung von Margen sind, genommen. Wenn Sie mit diesem Material vertraut sind, können Sie zu Abschnitt 3.OLS Regression überspringen Mit nicht-linearen Begriffen. Der Ränderbefehl kann nur verwendet werden, nachdem du eine Regression durchgeführt hast und auf die Ergebnisse des letzten Regressionsbefehls wirkt. Für unser erstes Beispiel laden wir den automatischen Datensatz, der mit Stata kommt und die folgende Regression ausführt. sysuse auto reg Preis mpg Verschiebung. Levels der Outcome Variable. Wenn Sie nur type. all von selbst, wird Stata den vorhergesagten Wert der abhängigen Variablen für jede Beobachtung, t berechnen Hen berichten den Mittelwert dieser Vorhersagen zusammen mit dem Standardfehler, t-statistisch usw. Wenn Margen einer kategorischen Variablen folgt, identifiziert Stata zuerst alle Ebenen der kategorischen Variablen. Dann berechnet für jeden Wert das, was der Mittel vorhergesagt hat Wert der abhängigen Variablen wäre, wenn alle Beobachtungen diesen Wert für die kategorische Variable hätten. Alle anderen Variablen bleiben unverändert. So fragt man zuerst, was wäre der Mittelpreis, wenn alle Autos inländisch waren, aber dennoch ihre vorhandenen Gewichte, Verschiebungen usw Und dann fragt, was wäre der mittlere Preis sein, wenn alle Autos fremd waren. Ist das gleiche für alle fünf Werte von rep78 aber da gibt es so viele von ihnen ist es ein guter Kandidat für eine grafische Darstellung Der marginsplot Befehl nimmt die Ergebnisse der vorherigen Margins Befehl und verwandelt sie in ein Diagramm. Für kontinuierliche Variablen Ränder offensichtlich können Sie alle möglichen Werte, aber Sie können festlegen, welche Werte, die Sie mit der Option an prüfen möchten. margins, bei Gewicht 2000 4000. Dies berechnet die durchschnittliche vorhergesagte Wert des Preises mit Gewicht auf 2000 Pfund gesetzt, und dann wieder mit Gewicht auf 4000 Pfund gesetzt Denken Sie an jeden Wert als Szenario die oben genannten Szenarien sind sehr einfach, aber Sie können machen Viel kompliziertere Szenarien durch Auflistung mehrerer Variablen und Werte in der at-Option Die Ränder-Ausgabe ordnet zuerst eine Nummer zu jedem Szenario zu, dann gibt sie ihre Ergebnisse nach Anzahl. Die Werte werden mit einer Numlist angegeben. Eine Numlist ist eine Liste von Zahlen wie eine Varlist Ist eine Liste von Variablen und, wie eine Varlist, gibt es viele verschiedene Möglichkeiten, um eine numlist definieren Typ help numlist, um sie alle zu sehen Die einfachste Methode ist nur, um die Zahlen, die Sie wollen, wie oben Sie können auch eine numlist mit der by Angabe des Anfangsintervalls end. margins, bei Gewicht 1500 500 5000. Dies berechnet den durchschnittlichen prognostizierten Wert des Preises mit Gewicht auf 1500, 2000, 2500, etc. bis zu 5000 Die tatsächlichen Gewichte reichen von 1760 bis 4840 Wieder ist dies ein guter KandidatFür eine grafische. Effekt eines Covariate. Wenn Sie die marginale Wirkung eines Kovariate oder die Ableitung des mittleren vorhergesagten Wertes in Bezug auf diese Kovariate betrachten wollen, verwenden Sie die Dydx-Option. In diesem einfachen Fall ist die Ableitung nur Der Koeffizient auf mpg, die immer der Fall für ein lineares Modell sein wird Aber erwägen, das Gewicht zu ändern, da das Modell sowohl Gewicht als auch Gewicht quadriert hat, müssen Sie berücksichtigen, dass beide Änderungen dieser Fall besonders verwirrend, aber nicht ungewöhnlich sind, weil der Koeffizient an Gewicht ist negativ, aber der Koeffizient auf Gewicht quadriert ist positiv So wird der Nettoeffekt des sich ändernden Gewichts für jedes gegebene Auto sehr viel von seinem Anfangsgewicht abhängen. Der Ränderbefehl kann sehr leicht Ihnen den mittleren Effekt erzählen. Was Margen hier ist, nehmen Sie die Numerische Ableitung des erwarteten Preises in Bezug auf das Gewicht für jedes Auto und berechnet dann den Mittelwert. Dabei betrachten die Ränder die tatsächlichen Daten. So betrachtet er die Wirkung der Veränderung des Hondes Ein Civic s Gewicht von 1.760 Pfund sowie das Ändern der Lincoln Continental s von 4.840 das Gewicht quadratischen Begriff ist wichtiger mit dem letzteren als das ehemalige Es dann durchschnittlich sie zusammen mit allen anderen Autos, um ihr Ergebnis von 2 362865 zu bekommen, oder dass Jedes zusätzliche Pfund des Gewichts erhöht die mittlere erwartete Preis um 2 36.To sehen, wie sich die Wirkung des Gewichts ändert sich als Gewicht ändert sich, verwenden Sie die Option erneut und dann die Ergebnisse. margins, dydx Gewicht bei Gewicht 1500 500 5000 marginsplot. This erzählt Uns, dass für niedrige Werte des Gewichts weniger als etwa 2000, steigendes Gewicht tatsächlich reduziert den Preis des Autos Allerdings für die meisten Autos zunehmende Gewicht erhöht Preis. Die Dydx-Option funktioniert auch für binäre Variablen. Jedoch, weil fremde in das Modell als eingegeben wurde Margen weiß, dass es nicht die Ableitung in Bezug auf Fremden nehmen kann, dh berechnen, was passieren würde, wenn alle Autos etwas fremder wurden. So berichtet es den Unterschied zwischen dem Szenario, wo alle Autos sind Sind ausländisch und das Szenario, wo alle Autos inländisch sind Sie können dies überprüfen, indem Sie laufen und machen die Subtraktion selbst. Binale Outcome-Modelle und Predicted Probabilities. The Margins Befehl wird sogar noch nützlicher mit binären Outcome-Modelle, weil sie immer nichtlinear Clear the Auto Datensatz aus dem Speicher und dann laden Sie den Grad von der SSCC-Website. Dies ist ein fiktiver Datensatz bestehend aus 10.000 Studenten Genau die Hälfte von ihnen sind hohe sozioökonomischen Status highSES und eine Hälfte sind nicht Genau die Hälfte jeder Gruppe wurde gegeben Intervention oder Behandlung behandeln, um die Wahrscheinlichkeit der Graduierung zu erhöhen Die Grad-Variable sagt uns, ob sie in der Tat absolvieren Ihre Ziele zu bestimmen, 1, ob die Behandlung einen Unterschied gemacht hat, und 2 ob die Wirkung der Behandlung durch sozioökonomischen Status SES unterschieden. Sie können die erste Frage mit einem einfachen logit model. logit grad behandeln highSES beantworten. Der Koeffizient auf Leckerei ist positiv und signifikant, suggestin G die Intervention erhöhte die Wahrscheinlichkeit der Graduierung Beachten Sie, dass highSES hatte einen noch größeren Einfluss. Next untersuchen, ob die Wirkung von SES durch Hinzufügen einer Interaktion zwischen den beiden. logit grad behandeln highSES. Der Koeffizient auf Behandlung highSES ist nicht signifikant unterschiedlich von Null Aber das bedeutet wirklich, dass die Behandlung genau die gleiche Wirkung hat, unabhängig von SES. Binäre Ergebnisse werden oft in Form von Odds Ratios interpretiert, also wiederholen Sie die vorherige Regression mit der oder Option, um sie zu sehen. logit grad behandeln highSES, oder. Dies sagt uns Dass die Chancen des Abschlusses, wenn Sie behandelt werden, sind ungefähr 2 83-mal die Chancen des Abschlusses, wenn Sie nicht behandelt werden, unabhängig von Ihrem SES Forscher manchmal verwirren Quotenverhältnisse mit Wahrscheinlichkeitsverhältnisse dh sie sagen, Sie sind 2 83-mal häufiger zu graduieren, wenn Sie Werden behandelt Dies ist falsch. Wenn Sie Margen bitten, die Interaktion zwischen zwei kategorischen Variablen zu untersuchen, wird es Szenarien für alle möglichen Kombinationen von denen schaffen Variablen Sie können dies verwenden, um leicht erhalten die vorhergesagte Wahrscheinlichkeit der Graduierung für alle vier möglichen Szenarien hohen SES niedrigen SES, behandelt nicht behandelt. Für niedrige SES Studenten, Behandlung erhöht die vorhergesagte Wahrscheinlichkeit der Graduierung von etwa 49 bis etwa 73 Für hohe SES Studenten, Behandlung erhöht die vorhergesagte Wahrscheinlichkeit der Graduierung von etwa 96 auf etwa 98 Nun, wenn Sie diese Wahrscheinlichkeiten in die Formel für die Berechnung der Odds Ratio, werden Sie feststellen, dass die Odds Ratio ist 2 83 in beiden Fällen verwenden die volle Zahlen aus der Ränder Ausgabe , Nicht die zweistelligen Approximationen, die hier gegeben werden, fügt die gleiche Menge der linearen Funktion hinzu, die in beiden Fällen durch die Logistikfunktion geleitet wird. Aber die Form der logistischen Funktion erinnern. Die Behandlung hat eine viel geringere Wirkung auf die Wahrscheinlichkeit der Graduierung für Hoch SES Studenten, weil ihre Wahrscheinlichkeit schon sehr hoch ist, kann es nicht viel höher werden Niedrige SES-Studenten sind in dem Teil der logistischen Kurve, die steigt Ply, so dass Änderungen in der linearen Funktion haben viel größere Auswirkungen auf die vorhergesagte Wahrscheinlichkeit. Der Ränder Befehl kann am häufigsten beantworten die Frage Ist die Wirkung der Behandlung variieren mit SE mit einer Kombination von dydx und at. margins, dydx behandeln bei highSES 0 1. Sie können auch dies mit Rändern HighSES, Dydx behandeln Wieder einmal sind diese die gleichen Zahlen, die Sie erhalten durch Subtraktion der Ebenen oben erhalten Wir schlagen immer auf Ebenen sowie Änderungen zu wissen, wo die Änderungen beginnen von gibt Ihnen ein viel Besseres Gefühl von dem, was los ist. Es ist eine allgemeine Regel, dass es am einfachsten ist, die vorhergesagte Wahrscheinlichkeit für Subjekte zu ändern, die am Rand sind, dh diejenigen, deren vorausgesagte Wahrscheinlichkeit nahe bei 0 5 beginnt. Dies ist jedoch eine Eigenschaft der logistischen Funktion, nicht der Daten Es ist eine Annahme, die Sie machen, wenn Sie ein Logit-Modell ausführen. Multinomial Logit. Multinomial Logit-Modelle können noch schwerer zu interpretieren, weil die Koeffizienten nur zwei Zustände vergleichen Clear Stata s Speicher und Loa D der folgende Datensatz, der sorgfältig konstruiert wurde, um die Fallstricke der Interpretation multinomialer Logitergebnisse zu veranschaulichen. Es enthält zwei Variablen, eine ganze Zahl y, die die Werte 1, 2 und 3 und eine stetige Variable x annimmt. Sie sind negativ korreliert cor y x. Now laufen das folgende Modell. Der Koeffizient von x für Ergebnis 2 ist negativ, so dass es s verlockend zu sagen, dass als x erhöht die Wahrscheinlichkeit von y 2 sinkt Aber in der Tat ist das nicht der Fall, wie die Margins Befehl wird Ihnen zeigen. margins, dydx x Vorhersage Ergebnis 2.The Vorhersage Optionen können Sie wählen, die Antwort Margen untersucht Vorhersage Ergebnis 2 spezifiziert, dass Sie Interesse an der erwarteten Wahrscheinlichkeit des Ergebnisses 2 Und in der Tat die Wahrscheinlichkeit des Ergebnisses 2 erhöht mit x das Derivat wird 0 016.Wie kann man sich erinnern, dass die Koeffizienten, die von mlogit gegeben werden, nur die Wahrscheinlichkeit eines gegebenen Ergebnisses mit dem Basisergebnis vergleichen. So sagt der x-Koeffizient von -5 34 für das Ergebnis 2, dass, wenn x zunimmt, beobachtet Tionen sind wahrscheinlich von Ergebnis 2 zum Ergebnis zu bewegen 1 Mittlerweile der x Koeffizient von -21 292 für Ergebnis 3 sagt Ihnen, dass als x erhöht Beobachtungen sind wahrscheinlich von Ergebnis 3 zu Ergebnis zu bewegen 1 Was es doesn t sagen, ist, dass, wie x erhöht Beobachtungen bewegen sich auch von Ergebnis 3 auf Ergebnis 2, und in der Tat, dass die Wirkung dominiert die Bewegung von 2 bis 1. Sie können es sehen, wenn Sie die Basiskategorie der Regression. mlogit yx, base 2.Now die Koeffizienten erzählen Sie über die Die Wahrscheinlichkeit eines jeden Ergebnisses im Vergleich zu dem Ergebnis 2 und die Tatsache, dass der negative x-Koeffizient für das Ergebnis 3 in absoluten Zahlen viel größer ist als der positive x-Koeffizient für das Ergebnis 1 zeigt an, dass die Erhöhung x die Wahrscheinlichkeit des Ergebnisses erhöht. 2. Wir empfehlen dringend, Margen zu verwenden Um zu erforschen, was deine Regressionsergebnisse bedeuten. Last überarbeitet 2 14 2014.3 Stata Graphics. Stata verfügt über ausgezeichnete Grafikeinrichtungen, die über den Graphenbefehl zugänglich sind, siehe Hilfegraph für eine Übersicht Die gängigsten Graphen in der Statistik S sind XY-Plots, die Punkte oder Linien zeigen. Diese sind in Stata über den twoway-Unterbefehl verfügbar, der wiederum 31 Unter-Unterbefehle oder Plot-Typen hat, von denen die wichtigste davon Streuung und Linie sind. Wir werden auch kurz Barplots beschreiben, die über die Bar Unterbefehl und andere Plot-Typen. Stata 10 führte einen Grafik-Editor, die verwendet werden können, um eine Grafik interaktiv zu modifizieren Wir nicht empfehlen diese Praxis, aber weil es im Widerspruch zu den Zielen der Dokumentation und Sicherstellung der Reproduzierbarkeit aller Schritte in Ihrer Forschung .3 1 Scatterplots. In diesem Abschnitt werden wir einige Plots veranschaulichen, die die Daten über den Fruchtbarkeitsabfall verwenden, die zuerst in Abschnitt 2 verwendet werden 1 Um die Daten von net-aware Stata type zu lesen. Um Ihren Appetit zu geben, hier ist die Handlung, die wir produzieren werden In diesem Abschnitt.3 1 1 Ein einfaches Scatterplot. Um ein einfaches Scatterplot der Fruchtbarkeitsänderung durch soziale Einstellung zu erzeugen, benutzt du den Befehl. Hinweis, den du zuerst spezitierst, dann markiert x Stata die Achsen mit den Variablenetiketten, wenn th Ey sind definiert, oder Variablennamen, wenn nicht Der Befehl kann abgekürzt werden twoway scatter oder einfach nur streuen, wenn das ist die einzige Handlung auf dem Diagramm Wir werden nun ein paar Glocken und Pfeifen hinzufügen.3 1 2 Fitted Lines. Suppose wir wollen zeigen Die passende Regressionslinie auch In einigen Paketen müssten Sie eine Regression durchführen, die passende Linie berechnen und dann plotten. Stata kann das alles in einem Schritt mit dem Lfit-Plot-Typ machen. Es gibt auch ein qfit-Plot für quadratische Passungen Mit dem Scatter-Plot kombiniert werden, indem man jedes Sub-Plot in Klammern einschließt. Man kann auch Plots mit zwei horizontalen Balken kombinieren, aber ich finde die Methode mit Klammern klarer. Angenommen, wir wollten Vertrauensbänder um die Regressionslinie setzen. Stata kann das mit machen Der lfitci-Plot-Typ, der die Vertrauensregion als graues Band zieht Es gibt auch ein qfitci-Band für quadratische passt Da das Vertrauensband einige Punkte verdecken kann, ziehen wir die Region zuerst und die Punkte später. Hinweis, dass dieser Befehl nicht t tippt t Er y-Achse aber verwendet eine Legende statt Sie können ein Etikett für die y-Achse mit der ytitle-Option angeben, und weglassen die eher offensichtliche Legende mit Legende aus Hier geben wir sowohl als Optionen auf die twoway Befehl Um die Option mehr offensichtlich zu machen Der Leser Ich stelle das Komma zu Beginn einer neuen Linie.3 1 3 Beschriftungspunkte. Es gibt viele Möglichkeiten, die es Ihnen erlauben, die Marker zu kontrollieren, die für die Punkte verwendet werden, einschließlich ihrer Form und Farbe, siehe Hilfe markeroptionen Es ist auch möglich Etikettieren Sie die Punkte mit Text in einer anderen Variable enthalten, mit der mlabel varname Option Im nächsten Schritt fügen wir die Ländernamen zum Plot hinzu. Ein geringes Problem mit den Etiketten ist die Überlappung von Costa Rica und Trinidad Tobago und in geringerem Maße Panama und Nicaragua Wir können dieses Problem lösen, indem wir die Position des Etiketts relativ zum Marker mit einer 12-Stunden-Uhr festlegen, also ist 12 oben, 3 ist nach rechts, 6 ist unten und 9 ist links und die mlabv-Option Wir erstellen ein Variable, um die Position einzustellen Default auf 3 Uhr und dann verschieben Costa Rica auf 9 Uhr und Trinidad Tobago nur ein bisschen darüber, dass um 11 Uhr können wir auch Nicaragua und Panama ein bisschen bewegen, sagen, um 2 Uhr. Die Grafik sieht dann wie folgt .3 1 4 Titel, Legenden und Untertitel. Es gibt Optionen, die für alle Zwei-Wege-Graphen gelten, einschließlich Titel, Etiketten und Legenden. Stata-Graphen können einen Titel und Untertitel haben, meist an der Spitze und eine Legende-Note und Beschriftung in der Regel An der Unterseite geben Sie Hilfe titleoptions, um mehr zu erfahren Normalerweise ist ein Titel alles, das Sie benötigen Stata 11 erlaubt Text in den Graphen, fett, kursiv, griechische Buchstaben, mathematische Symbole und eine Wahl der Schriftarten einzuschließen, geben Sie Hilfegraphtext, um mehr zu lernen Endgültige Tweak auf die Grafik wird, um eine Legende hinzufügen, um die lineare Passung und 95 Konfidenz Intervall, aber nicht Fruchtbarkeit abnehmen selbst Wir tun dies mit der Bestellung 2 lineare Passung 1 95 CI Option der Legende, um die zweite und erste Elemente in Diese Bestellung Wir verwenden auch Ring 0, um die Legende im Plottenbereich zu bewegen , Und pos 5, um die Legende-Box in der Nähe der 5-Uhr-Position zu platzieren. Unser vollständiger Befehl ist dann. Das Ergebnis ist die Grafik am Anfang dieses Abschnitts gezeigt Wenn Ihr Diagramm sieht etwas anders ist es wahrscheinlich, weil wir verschiedene Farbschemata verwendet, die ich verwendet habe Eine benutzerdefinierte Version von s2color Siehe 3 2 5 unten für weitere Informationen über Schemata.3 1 5 Achsen Skalen und Etiketten. Es gibt Optionen, die die Skalierung und Reichweite der Achsen, einschließlich xscale und yscale, die arithmetisch, log oder umgekehrt werden können steuern , Geben Sie help axisscaleoptions ein, um mehr zu erfahren Andere Optionen steuern das Plazieren und Etikettieren von Major und Moll Ticks und Labels, wie zB xlabel xtick und xmtick und ähnlich für die y-Achse, siehe help axislabeloptions Normalerweise sind die Vorgaben akzeptabel, aber es ist schön Zu wissen, dass Sie sie ändern können.3 2 Line Plots. I wird illustrieren Linienplots mit Daten über die US-Lebenserwartung, verfügbar als einer der Datensätze mit Stata versendet Versuchen Sie sysuse dir zu sehen, was noch verfügbar ist. Die Idee ist zu plotten Lebenserwartung für weiße und schwarze Männer über dem 20. Jahrhundert Wiederum, um deinen Appetit zu heben, fange ich an, indem du dir das Endprodukt zeigst, und dann werden wir das Diagramm bitweise bauen. 2 1 Ein einfaches Linienplot. Das einfachste Plot verwendet Alle defaults. If Sie sind durch das Dip vor 1920 verwirrt, Google US Lebenserwartung 1918 Wir könnten den Befehl zu twoway Linie oder sogar Linie abkürzen, wenn das s alles, was wir plotten Diese Verknüpfung funktioniert nur für Streuung und line. The Linie Plot ermöglicht Sie geben mehr als eine y-Variable an, die Reihenfolge ist y 1 y 2 ymx In unserem Beispiel haben wir zwei angegeben, was der weißen und schwarzen Lebenserwartung entspricht. Alternativ könnten wir zwei Linienplots verwendet haben, Titles and Legends. Die Standard-Grafik ist ziemlich gut, aber die Legende scheint zu wortig Wir werden die meisten Informationen auf den Titel zu bewegen und halten nur Ethnizität in der Legende. Hier haben wir drei Optionen, die wie üblich in Stata nach einem Komma gehen Titeluntertitel und Legende Die Legende opt Ion hat viele Sub-Optionen, die wir bestellt haben, um die Schlüssel und ihre Etiketten aufzulisten, sagen, dass die erste Zeile vertreten Weiß und die zweiten Schwarzen Um einen Schlüssel zu verlassen, lassen Sie es einfach aus der Liste Um Text ohne einen passenden Schlüssel hinzufügen, verwenden Sie einen Bindestrich oder Minuszeichen für den Schlüssel Es gibt viele andere Legende-Optionen, siehe Hilfe legendoption, um mehr zu lernen. Wir möchten den Platz ein bisschen besser nutzen, indem wir die Legende in den Plotbereich bewegen, sagen wir rund um die 5 Uhr Position, wo die Verbesserung der Lebenserwartung hat Verließ etwas Ersatzteil Wie bereits erwähnt, können wir die Legende im Inneren des Plottenbereichs bewegen, indem wir Ring 0 den inneren Kreis benutzen und ihn in der Nähe der 5-Uhr-Position mit Pos 5 platzieren. Weil diese Legenden-Unteroptionen sind, müssen sie in die Legende gehen. 3 2 3 Line Styles. I don t wissen über Sie, aber ich finde schwer zu unterscheiden, die Standard-Linien auf der Handlung Stata können Sie den Linienstil auf unterschiedliche Weise kontrollieren Die Clstyle-Option können Sie einen benannten Stil, wie Vordergrund Raster yxline verwenden Oder p1-p15 für die verwendeten Stile b Y Zeilen 1 bis 15, siehe Hilfe linestyle Dies ist nützlich, wenn Sie Ihre Stilelemente aus einem Schema auswählen möchten, wie weiter unten beschrieben wird. Alternativ können Sie die drei Komponenten eines Stils mit dem Linienmuster, der Breite und der Farbe angeben. Die Muster sind angegeben Verwenden Sie die Clpattern-Option Die häufigsten Muster sind solide Bindestrich und Punkt sehen Hilfe linepatternstyle für weitere Informationen. Line Breite wird mit Clwidth angegeben die verfügbaren Optionen gehören dünne Medium und dick sehen h elp linewidthstyle für more. Colors können mit der Clcolor-Option mit angegeben werden Farbnamen wie rote weiße und blaue Knickenten-Siena und viele andere oder RGB-Werte, siehe Hilfe colorstyle. Hier s, wie man blau für Weiß und rot für blacks. Note, dass clcolor ist eine Option der Linie Plot, so dass wir Klammern runden Die Zeile Befehl und steckte es dort.3 2 4 Skala Optionen. Es sieht aus, als ob Verbesserungen in der Lebenserwartung verlangsamt ein bisschen in der zweiten Hälfte des Jahrhunderts Dies kann besser geschätzt werden mit einem Log-Skala, wo Eine gerade Linie würde eine konstante prozentuale Verbesserung anzeigen. Dies geschieht leicht mit den Achsenoptionen des Zwei-Wege-Befehls, siehe Hilfe-Achsenoptionen und insbesondere yscale, mit denen du Arithmetikprotokoll oder umgekehrte Skalen auswählen kannst. Es gibt auch einen Unteroptionsbereich, um das Plotten zu steuern Bereich Hier werde ich den y-Bereich als 25 bis 80 angeben, um die Kurven ein bisschen hoch zu bewegen.3 2 5 Graph Schemes. Stata verwendet Schemata, um das Aussehen von Graphen zu steuern, siehe Hilfeschema Sie können das Standardschema festlegen, das verwendet werden soll Alle grafiken mit set schemename Sie können auch die letzten grafiken mit einem anderen schema mit grafische darstellung, schema schemename. To sehen, um eine Liste der verfügbaren Schemata zu sehen Typ grafische Abfrage, Schemata Versuchen Sie s2color für Bildschirmgraphen, s1manual für den Stil, der in den Stata Handbüchern verwendet wird , Und Ökonom für den Stil, der in The Economist verwendet wird. Mit dem letzteren erhalten wir den Graphen, der am Anfang dieses Abschnitts gezeigt wird.3 3 Managing Graphs. Stata verfolgt den letzten Graphen, den du gezeichnet hast, der im Speicher gespeichert ist, und Nennt es Graph Sie können tatsächlich mehr als ein Diagramm im Speicher behalten, wenn Sie die Namensoption verwenden, um den Graphen zu benennen, wenn Sie ihn erstellen. Dies ist nützlich für die Kombination von Graphen, geben Sie Hilfe Graph kombinieren, um mehr zu erfahren Beachten Sie, dass Graphen im Speicher verschwinden, wenn Sie Beenden Sie Stata, auch wenn Sie die Daten speichern, es sei denn, Sie speichern die Grafik selbst. Um das aktuelle Diagramm auf der Festplatte mit dem eigenen Format von Stata zu speichern, geben Sie grafisch ein, um den Dateinamen zu speichern. Dieser Befehl hat zwei Optionen, die Sie verwenden müssen, wenn Sie die Datei bereits verwenden möchten Existiert und asis, die den Graphen mit seinem aktuellen Stil einfriert und dann speichert. Der Standardwert ist, den Graphen in einem Live-Format zu speichern, das in zukünftigen Sessions bearbeitet werden kann, zB durch Ändern des Schemas. Nach dem Speichern eines Graphen im Stata-Format kannst du Laden Sie es von der Festplatte mit dem Befehlsgraph verwenden Dateiname Beachten Sie, dass die Grafik speichern und die Grafik verwenden, um zu speichern und zu verwenden für Stata-Dateien Jeder Graphen, der im Speicher gespeichert ist, kann mit der Grafikanzeige angezeigt werden. Sie können auch auflisten, beschreiben, umbenennen, kopieren oder oderDrop-Graphen im Speicher gespeichert, geben Sie Hilfe Graphmanipulation, um mehr zu lernen. Wenn Sie planen, die Grafik in ein anderes Dokument zu integrieren, müssen Sie wahrscheinlich müssen, um es in einem tragbaren Format zu speichern Stata s Befehl Graph Export Dateiname kann die Grafik mit einer Vielzahl von exportieren Vektor - oder Rasterformate, die in der Regel aus der Dateierweiterung verstanden werden. Vektorformate wie Windows Metafile wmf oder emf oder Adobe s PostScript und deren Varianten ps, eps, pdf enthalten im Wesentlichen Zeichnungsanweisungen und sind somit auflösungsunabhängig, also sind sie am besten für die Aufnahme In anderen Dokumenten, in denen sie verkleinert werden können Rasterformate wie Portable Network Graphics png speichern das Bild pixelweise mit der aktuellen Bildschirmauflösung und sind am besten für die Aufnahme in Webseiten geeignet. Sie können auch eine Grafik mit Graphendruck drucken oder kopieren und einfügen Es in ein Dokument mit der Windows-Zwischenablage, um dies zu tun, klicken Sie mit der rechten Maustaste auf das Fenster mit dem Diagramm und wählen Sie dann Kopie aus dem Kontextmenü aus. 2017 Germ n Rodr guez , Princeton University. Wie kann ich den Ränder Befehl verwenden, um mehrere Interaktionen in der logistischen Regression zu verstehen Stata 11 Stata FAQ. The Margins Befehl, neu in Stata 11, kann ein sehr nützliches Werkzeug zum Verständnis und Interpretation von Interaktionen werden Wir veranschaulichen den Befehl für ein Logistische Regressionsmodell mit zwei kategorischen durch kontinuierliche Interaktionen Wir beginnen mit dem Laden des Datensatzes mlogcatcon. In diesem Datensatz y ist die binäre Antwort Variable und m und s sind kontinuierliche Prädiktoren Die Variable f, die für weiblich steht, ist ein binärer Prädiktor Wir werden interagieren f mit Sowohl m als auch s Hier ist das logistische Regressionsmodell. Sie werden feststellen, dass die f durch s Interaktion statistisch signifikant ist, während das f durch m Interaktion nicht ist. Da es sich um ein nichtlineares Modell handelt, müssen wir die Werte aller Kovariaten berücksichtigen Verständnis dessen, was im Modell vor sich geht. Wir werden mit einem Margin-Befehl beginnen, der den diskreten Unterschied in der Wahrscheinlichkeit zwischen Männern und Frauen für fünf d betrachtet Ifferent-Stufen von s bei gleichem m-Wert mit dem Mittelwert Wir erhalten den diskreten Unterschied in der Wahrscheinlichkeit mit der dydx-Option mit dem Binär-Prädiktor Die Variable m wird mit dem Mittelwert mit dem Mittelwert gehalten. Während die Ergebnisse des Ränderbefehls oben sind Vollkommen korrekt, spiegeln sie die diskrete Veränderung der Wahrscheinlichkeit für nur einen einzigen Wert von m Wenn wir die atmeans Option entfernen, erhalten wir den durchschnittlichen Randeffekt, dh die diskrete Veränderung der Wahrscheinlichkeit für jeden der Werte von s, die über die beobachteten Werte von m gemittelt werden Hier ist, wie die Ränder Befehl aussieht. Let s gehen Sie vor und grafisch diese Ergebnisse einschließlich der 95 Konfidenzintervalle Wir werden beginnen, indem Sie Platzierung notwendigen Werte in eine Matrix mit Techniken in Stata FAQ Wie kann ich die Ergebnisse der Ränder Befehl Die Grafik Matrix-Befehle wird von einem Twoway-Line-Graphen gefolgt. Der Margins-Befehl und der Graph oben geben uns eine ziemlich gute Vorstellung davon, wie sich die diskrete Veränderung der Wahrscheinlichkeit über diff unterscheidet Aber wir wissen immer noch nicht, wie sich das mit unterschiedlichen Werten von m ändert. Lass den Ränder-Befehl noch einmal versuchen, diesmal variiert sowohl s als auch m. Die ersten fünf Zeilen geben die diskrete Veränderung für die fünf Werte von s während Halten m bei 30 Die nächsten fünf halten m bei 40 Und so weiter Eines der interessanteren Merkmale ist, wie wenige der diskreten Veränderungen statistisch signifikant sind, obwohl die Gesamtheit der Interaktion signifikant war. Jetzt können wir die notwendigen Werte in ein Matrix in Vorbereitung für graphing. Let s beginnen durch die graphische Darstellung der Wirkung von verschiedenen Werten von s mit separaten Linien für jeden Wert von m. Obwohl es nicht viele signifikante Werte in der Ränder Tabelle oben, die Zeilen für jeden der Werte von Ich sehe ziemlich unterschiedlich von einander Während die Linie für m gleich 30 ist eher flach die Linie für m gleich 70 zeigt viel mehr Variabilität, zuerst fallen und dann steil um s gleich 50.Now, dass wir wissen, welche Unterschiede in s für Werte von M sieht aus, wir können die Variablen in der Grafik-Befehls-Twoway-Zeile umkehren, um zu sehen, welche Unterschiede in m für Werte von s aussieht. Natürlich sehen wir die gleichen 25 Werte wie die vorherige Grafik, die gerade anders organisiert ist Line für s gleich 70 ist derjenige, der sich von den anderen abhebt. Wenn dein Modell komplexer ist als dieses, musst du entscheiden, was mit jedem der Kovariaten zu tun ist. Du kannst sie bei einem oder mehreren Werten konstant halten oder du kannst Durchschnitt über sie Was auch immer du brauchst zu erkennen, dass die Werte aller Kovariaten in nichtlinearen Modellen ausmachen. Hi Sie könnten versuchen, diese dreistufige Prozess 1 Regress finanzielle Unterstützung auf Rennen 2 erhalten die vorhergesagten Werte mit Rändern 3 erstellen Sie die Bar Diagramm mit marginsplot. Something wie this. reg Finanzielle Hilfe sicher sein, die i-dot vor dem Rennen verwenden, um auf Stata, dass Race ist eine ungeordnete kategorische Variablen. margins, über Race Marginsplot, x Race Reast Bar. Ich bin sicher, dass es einen Weg Um dies mit twoway zu tun Bar Auch, es hilft, wenn Sie den Code, den Sie verwendet haben. Will versuchen, dass danke, obwohl es scheint ein bisschen beteiligt für die Erlangung einer einfachen Zusammenfassung der Anteil der Menschen auf finanzielle Hilfe. Mein Code Ich habe im Moment verwendet, ist dies. Histogramm FinancialAid, diskrete Prozent von Race. This Code ist fast das, was ich will, außer es zeigt die 0s von Race als auch, und doesn t zeigen die genauen Prozentsätze von jedem - Sie sortieren müssen, um den Anteil zu gucken. Dies ist dokumentiert Verwenden Sie die Blabel option. Sie sagten, dass Ihre Variable 0-1 war, in welchem ​​Fall sein Mittel in diesem Intervall sein wird irgendwie Sie erhielten eine prozentige Skala, also ist das, was Sie wünschten. Der Titelprozent des Mittelwertes von FinancialAid würde besser sein, als etwas wie Prozent an Finanzielle Hilfe. Sie brauchen keine Legende hier Ihre Kategorien passen gut als Achs-Labels. Showing die genaue Syntax, die Sie verwendet wird empfohlen. Last bearbeitet von Nick Cox 28 Apr 2014, 02 14. Eine bessere Möglichkeit, Ihre Daten anzuzeigen ist zu verwenden Horizontale Balken Damit kann der Legendentext abgebrochen werden D Der Leser kann die Identität der Kategorie und den Prozentsatz in einer einzigen horizontalen Bewegung lesen. Ich habe keine anderen Farben für verschiedene Rennen verwendet, da alle Balken die gleiche Sache zeigen und die Farben nicht mehr benötigt werden, um einzelne Balken zu verknüpfen Ihre Etiketten. Ich habe auch die vertikale Dimension des Diagramms verwendet, um die relative Größe jeder Kategorie zu zeigen, anstatt sie in einer beliebigen Reihenfolge zu haben, wie Sie hatte. Dies geschah mit Nick Cox s - catplot - Befehl habe ich Frequenzgewichte verwendet Geben Sie die Größe der einzelnen bar. catplot rvrace fw percent. An Einführung in Stata Graphics. Stata enthält eine Vielzahl von Werkzeugen für die Erstellung von Publikations-Qualität Grafiken Zwischen der Vielzahl von Grafiken, die Sie machen können und die schiere Anzahl der Details, die Sie kontrollieren können Ein Diagramm, Stata-Grafiken können ein gewaltiges Thema sein Allerdings müssen Sie wahrscheinlich nur noch ein paar verschiedene Arten von Graphen machen, und in den meisten Fällen Stata s Standard-Einstellungen werden in Ordnung Was ist mehr, Stata s Graphical User Interface GUI organisiert die verschiedenen Grafikoptionen auf eine intuitive Art und Weise, so dass Sie sie finden können, wenn Sie sie benötigen, ohne die Syntax für jeden einzustellen. Das bedeutet nicht, dass Sie Ihre Grafikbefehle nicht in die Dateien einfügen müssen, sobald Sie sie erstellt haben, aber das bedeutet Dass für komplexe Graphen können Sie die GUI verwenden, um die Befehle zu erstellen, die Sie speichern. Stata 10 hat auch einen Grafik-Editor hinzugefügt, mit dem Sie eine Grafik ändern können, nachdem Sie es erstellt haben. Dies gibt Ihnen noch mehr Kontrolle über Ihre Grafik, aber im Gegensatz zu der GUI Für die Erstellung eines Graphen gibt Ihnen der Herausgeber keinen Befehl, den Sie später erneut ausführen können. Wenn Sie später Änderungen an Ihren Daten vornehmen, müssen Sie Ihre Grafik von vorne anfangen. So ist es besser, die Grafik zu erstellen, die Sie an erster Stelle haben wollen Wo möglich, aber der Redakteur ist immer noch eine sehr nützliche Ergänzung. Dieser Artikel diskutiert die Erstellung von Graphen mit der Stata GUI, die Struktur der Grafik-Befehlssyntax ohne zu viel auf die Details, einige gängige Arten von Graphen und den Grafik-Editor zu verweilen Sie sollten einige Vertrautheit mit grundlegenden Stata vor Beginn, wenn Sie don t, betrachten beginnen mit Stata für Forscher oder Stata für Studenten Der beste Weg, um diesen Artikel zu verwenden ist, um es am Computer zu lesen und tatsächlich durchführen die Schritte beschrieben Die Beispiele in diesem Artikel wird die Automobil-Dataset verwenden, die mit Stata kommt, also fange an, indem du sie tippst, um es zu laden. Fühlen Sie sich frei zu experimentieren, wie Sie gehen, vor allem mit den Einstellungen, die wir nicht diskutieren, weil sie entweder ziemlich offensichtlich oder selten verwendet werden Erstellen eines Graphen wird niemals Ändern Sie Ihre Daten, so dass das Schlimmste, was passieren kann, ist, dass Ihre Grafik entpuppt sich als nutzlos oder einfach nur hässlich. Creating Graphs mit der grafischen Benutzeroberfläche. Wir beginnen mit einem einfachen Scatter-Plot mit Gewicht als die X-Variable und mpg als die Y Variable Stata bezieht sich auf jeden Graphen, der eine Y-Variable und eine X-Variable als Twoway-Graph hat, also klicken Sie auf Graphics Twoway-Graph Der nächste Schritt ist, ein Plot zu definieren In Stata-Begriffe ist ein Plot einige spezifische Daten visualisiert In einer bestimmten Weise, zum Beispiel eine Streuung von mpg auf Gewicht Ein Diagramm ist ein ganzes Bild, einschließlich Achsen, Titel, Legenden, etc. Auch ein einzelnes Diagramm kann mehrere Plots enthalten Das grundlegende twoway Dialogfeld ermöglicht es Ihnen, so viele zu definieren Plots, wie Sie es brauchen, und kontrollieren Sie die anderen Eigenschaften des Graphen. Um ein Plot zu definieren, klicken Sie auf Create You ll dann erhalten Sie ein Dialogfeld, wo Sie die Plot, die Sie wollen, die Kategorie gesetzt auf Basic Plots und die Art auf Scatter For gesetzt Die Y-Variable auswählen oder geben Sie mpg und für die X-Variable select oder geben Sie Gewicht ein Hinweis Linux Stata erlaubt Ihnen nicht, Variablen auszuwählen, damit Sie ihre Namen eingeben müssen In Windows Stata können Sie entweder. Wenn Sie auf Submit die Grafik klicken 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.

Comments

Popular posts from this blog

Vz58 Aktienoptionen

Langkah Pertama Bermain Forex Handel

Symbolismus Von Drei Schwarz Krähen