Search code examples
stata

How do you align labels using -graph hbar- in Stata?


I want to visually align the labels for "Cats" and "Apples" so that they appear on the same "line", and to do the same for "Dogs" and "Apples", rather than having the animal label appear in the middle of the list of fruit labels. Is this possible using graph hbar?

input str10(fruit animal) float value
"Apples"    "Cats" 31.8
"Bananas"   "Cats" 16.7
"Mangos"    "Cats" 17.9
"Pears"     "Cats" 18.1
"Apples"    "Dogs" 1.6
"Bananas"   "Dogs" 4.3
"Mangos"    "Dogs" 4.4
end

graph hbar (asis) value, over(fruit) over(animal) nofill

example_plot

Red arrows show where I want the animal label to be.


Solution

  • I also feel there should be an easy(/easier) way of doing this. I got what I think you're after in the graph editor (see below), and this is the contents of the .grec file:

    StataFileTM:00001:01100:GREC:                          :
    00006:00006:00001:
    *! classname: hbargraph_g
    *! family: bar
    *! date:  2 Jun 2021
    *! time: 21:41:23
    *! graph_scheme: cleanplots
    *! naturallywhite: 1
    *! end
    
    // File created by Graph Editor Recorder.
    // Edit only if you know what you are doing.
    
    .supaxis.add_ticks 90 `"Cats"', tickset(major)
    // supaxis edits
    
    .supaxis.major.num_rule_ticks = 0
    .supaxis.edit_tick 3 90 `"Cats"', tickset(major)
    // supaxis edits
    
    .supaxis.add_ticks 30 `"Dogs"', tickset(major)
    // supaxis edits
    
    .supaxis.major.num_rule_ticks = 0
    .supaxis.edit_tick 4 30 `"Dogs"', tickset(major)
    // supaxis edits
    
    .supaxis.major.delete_tick 1
    // supaxis edits
    
    .supaxis.major.delete_tick 1
    // supaxis edits
    
    
    // <end>
    

    I'm not sure that's going to be too helpful for you unfortunately, but that's the best i can manage right now (hopefully it's better than nothing though!).

    To get it to work, I went into the graph editor, selected the option to edit/add individual ticks, and then added one for 'Cats' at point 90 on the y-axis and one for 'Dogs' at point 30. I then deleted the other two y-axis labels that Stata had automatically created. I can't attach the .grec file to this post but you can copy the above into a text editor of your choice.

    FYI, .grec files are saved by default in a grec folder which Stata looks for in your personal directory. If you don't know where that is you can find it by typing sysdir into your console; if you don't have one you can just make that path manually.

    enter image description here