Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Two histograms for a continuous variable across categories of a dichotomous variable with normal curves

    I am trying to make a histogram for a continuous variable 'length' across the categories of a dichotomous variable 'foreign' with normal curves for both histograms. I want both histograms in the same graph.
    I tried using the code:
    Code:
    sysuse auto
    hist length if foreign == 0, fcolor(blue%50) normal addplot(hist length if foreign == 1, fcolor(green%30) normal)
    but it throws an error message
    option normal not allowed
    KIndly advise how to fix this.
    I am looking to construct a graph like this here in the attached image:

    Click image for larger version

Name:	hist2.jpg
Views:	1
Size:	64.2 KB
ID:	1643657
    Last edited by Inaamul Haq; 05 Jan 2022, 03:34.

  • #2
    addplot() is to add a graph twoway plot, which hist is not.

    Here is some technique.


    Code:
    sysuse auto, clear
    
    su mpg if foreign == 0 
    local mu0 = r(mean)
    local sd0 = r(sd)
    local min = r(min)
    local max = r(max)
    
    su mpg if foreign == 1 
    local mu1 = r(mean)
    local sd1 = r(sd)
    local min = min(`min', r(min)) - 3
    local max = max(`max', r(max)) + 3 
    
    twoway histogram mpg if foreign == 0, width(2) blcolor(red) bfcolor(red%10) ///
    || function normalden(x, `mu0', `sd0'), ra(`min' `max') lcolor(red) ///
    || histogram mpg if foreign == 1, width(2) blcolor(blue) bfcolor(blue%10) ///
    || function normalden(x, `mu1', `sd1'), ra(`min' `max') lcolor(blue) /// 
    legend(order(1 "Domestic" 3 "Foreign")) xtitle("`: var label mpg'") ytitle(Density)
    Click image for larger version

Name:	hist.png
Views:	1
Size:	25.6 KB
ID:	1643670


    I would recommend instead a normal quantile plot using qplot from the Stata Journal.


    Code:
    qplot mpg, over(foreign) trscale(invnormal(@)) xla(-2/2) xtitle(standard normal deviate) aspect(1) yla(, ang(h))
    The quantile plot allows direct comparison of each subset with the other and with normal reference distributions without obliging arbitrary decisions on bin start and width.

    Click image for larger version

Name:	qplot.png
Views:	1
Size:	22.5 KB
ID:	1643671

    Comment


    • #3
      A detailed edit of #2 might move the legend inside the plot region: there is enough space to do that. Also, Foreign plots above Domestic, so that would make sense for the legend. I would not rule out little Ds and Fs as being an alternative to marker symbols.

      Comment

      Working...
      X