Search code examples
graphbar-chartstatagrouped-bar-chart

What is the simplest way to make a grouped bar graph where you can input your own values in Stata?


I've got say two groups a and b and a has values (4, 8, 2, 4, 2) and b has values (1, 5, 2, 8, 7) for time points 1, 2, 3, 4, 5. How do I make a bar graph out of these values without having to clear my data set and make new variables?

Time will be the x axis and value will be the y axis.


Solution

  • You need new variables but they don't have to be aligned with existing data. Several ways to do it. You could type in new variables in the Data Editor or use input, or here is self-contained code with some of the many ways to do it.

    clear 
    
    mat a = (4, 8, 2, 4, 2) 
    mat b = (1, 5, 2, 8, 7) 
    mat t = (1, 2, 3, 4, 5) 
    
    set obs 10 
    gen y = a[1, _n] 
    replace y = b[1, _n-5] in 6/10 
    gen t = t[1, _n]
    replace t = t[1, _n-5] in 6/10 
    gen which = cond(_n <= 5, "a", "b")
    
    set scheme s1color 
    graph bar (asis) y, over(t) over(which)
    
    gen a = a[1, _n] 
    gen b = b[1, _n]
    
    graph bar (asis) a b in 1/5, over(t) 
    
    gen t1 = t-0.2
    gen t2 = t+0.2
    
    twoway bar a t1, barw(0.4) || bar b t2, barw(0.4) xla(1/5) legend(pos(12) row(1)) xtitle(t)
    

    You should omit the command

    set obs 10
    

    if you already have 10 or more observations in the dataset.