Announcement

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

  • How to make some modifications to a graph bar?

    Hello everyone!
    Suppose I want to create a graph bar such as:

    Code:
    clear all
    sysuse auto
    
    drop if trunk>16
    generate index = _n
    gen div = index/3
    gen mark = 1 if div == floor(div)
    replace foreign = 2 if mark == 1
    
    graph bar (percent), over(foreign) by(trunk)
    Now, suppose I only want the bars corresponding to foreign == 1 and foreign == 2 to show. The first possible solution that came to my mind was:

    Code:
    graph bar (percent) if foreign != 0, over(foreign) by(trunk)
    but there is an evident problem, i.e. that the percentages are computed on the new restricted sample, rather than the original number of observations.
    How do I avoid this?

    Also, suppose that, instead of 12 different graph bars for each value of trunk, I wanted a single graph bar with trunk on the x-axis and the two columns for foreign == 1 and foreign == 2 joined side by side. How can I do that?

  • #2
    Often, it is necessary to calculate the percentages beforehand and plot these percentages. For #2, you need two -over()- options instead of -by()-.

    Code:
    clear all
    sysuse auto
    
    drop if trunk>16
    generate index = _n
    gen div = index/3
    gen mark = 1 if div == floor(div)
    replace foreign = 2 if mark == 1
    
    bys trunk: gen pct=_N
    bys trunk foreign: replace pct= (_N/pct)*100
    
    set scheme s1color
    graph bar pct if foreign, over(foreign) over(trunk) ///
    asyvars blab(total, format(%3.0f)) nofill ///
    ytitle(Foreign (Percent), size(medium)) ///
    legend(order(1 "1" 2 "2") ring(0) pos(1) col(1)) ///
    ysc(r(0 110)) ylab("") b1title(Trunk)
    Click image for larger version

Name:	Graph.png
Views:	1
Size:	22.1 KB
ID:	1719836


    Last edited by Andrew Musau; 09 Jul 2023, 07:39.

    Comment


    • #3
      Thanks a lot!

      Comment

      Working...
      X