Announcement

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

  • Changing the legend label in a stack bar chart

    How can I change the labels in the legend of a stack bar chart?

    Code:
    clear
    input year industry_a industry_b  
    2020 120 80 
    2021 130 90
    end
    
    graph bar industry_a industry_b, over(year) stack
    why
    Code:
    legend(label(1 "a" 2 "b"))
    does not work?

  • #2
    Code:
    legend(label(1 "a") label(2 "b"))

    Comment


    • #3
      Chen Samulsion is right, but there is another way to do it, and with your example you're better off changing the order anyway.

      The data example in #1 is small enough to show your problem, which is exactly right, but stacked bars tend to become less effective -- to read and to show well -- very quickly for (presumably in your case) several industries and several years.

      Among various alternatives are

      line plots -- a serious contender often, but not illustrated here --

      and twoway bar charts as implemented in tabplot from the Stata Journal. See e.g. https://www.statalist.org/forums/for...updated-on-ssc for the sales pitch and various quick examples and https://www.stata-journal.com/articl...article=gr0066 for the paper but

      Code:
      search tabplot, sj
      for the latest public update.


      Code:
      clear
      input year industry_a industry_b  
      2020 120 80 
      2021 130 90
      end
      
      * use order() within legend()
      graph bar industry_a industry_b, over(year) stack legend(order(2 "b" 1 "a")) name(G1, replace)
      
      * another way to do it 
      reshape long industry_, i(year) j(which) string 
      
      tabplot which year [iw=industry_], subtitle(whatever) showval separate(which) name(G2, replace)
      Naturally both graphs are trivial at the moment and need better and/or extra text. The issues for real examples include, but are not limited to,

      1. the space needed to show a legend if the number of categories is more like say 10 or 30

      2. the mental back and forth implied between plot and legend if you use a legend at all

      3. how effective the stacked design will be if you have small values too

      4. reliance on different colours with a stacked design (with the twoway bar chart, colours are cosmetic and not essential to distinguish categories)

      5. how easily you can read off numbers if you want to do that.
      Click image for larger version

Name:	hossein_G1.png
Views:	1
Size:	25.4 KB
ID:	1771660
      Click image for larger version

Name:	hossein_G2.png
Views:	1
Size:	26.2 KB
ID:	1771661



      Comment

      Working...
      X