Announcement

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

  • Creating Bar Graph colors depending on Y-value

    Hello:
    I am having trouble creating a bar graph where the color of the bars depend on the y-value they represent. I am able to do this manually, but I'd like to have code to do it systematically, so that if I wanted to create a graph for a specific observation group, the color would be dependent on a certain "level".

    I have tried using the cond( ) command as well as the -if- expression in many iterations, as well as using macros but I am just not getting it to work out.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id level) str7 area str6 col
    1 1 "kitchen" "lime"  
    1 1 "dining"  "lime"  
    1 1 "bed"     "lime"  
    4 5 "bed"     "red"   
    4 3 "garage"  "yellow"
    5 4 "dining"  "orange"
    end
    Essentially, I would like level to be on the y axis and depending on what value that y shows, the bar graph color will automatically change.
    I would also like to "hone" in on certain IDs only to isolate them and only graph their data:

    This is how I would manually create graph for id==1:
    Code:
    graph bar (asis) level if id==1, over(area) bar(1, fcolor(lime))
    How could I program the "lime" to appear since the level == 1.
    What if the level was 3?

    I'd like it to automatically make the bar yellow as if somehow I were saying
    Code:
    bar(1,fcolor(`col'))
    Thank you.


  • #2
    I don't know a way to do what you want that is very different from what you know already.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float(id level) str7 area str6 col
    1 1 "kitchen" "lime"  
    1 1 "dining"  "lime"  
    1 1 "bed"     "lime"  
    4 5 "bed"     "red"  
    4 3 "garage"  "yellow"
    5 4 "dining"  "orange"
    end
    
    separate level, by(level) veryshortlabel
    
    graph bar (asis) level?, over(id) over(area) bar(1, color(lime)) bar(2, color(yellow)) bar(3, color(orange)) bar(4, color(red)) nofill legend(off) ytitle(level) yla(, ang(h))
    The example shows what is tricky here. You have values 1 3 4 5, so the second bar plotted is for outcome 3.

    graph bar won't show an empty bar for an absent value, here 2.

    For finer control, you would probably need to switch to twoway bar.

    A different point: combinations of red and green are generally advised against as many people have difficulty in distinguishing them.
    Last edited by Nick Cox; 11 Apr 2023, 02:56.

    Comment

    Working...
    X