Announcement

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

  • Change legend automatically in graph

    Dear Statalists,

    Suppose I have a data like this

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str5 id int(year data)
    "a123"  2015 190
    "a123"  2016 172
    "a123"  2017 227
    "as433" 2015 232
    "as433" 2016 167
    "as433" 2017 119
    "te398" 2015 193
    "te398" 2016 239
    "te398" 2017 156
    "be372" 2015 185
    "be372" 2016 136
    "be372" 2017 148
    "cd923" 2015 135
    "cd923" 2016 213
    "cd923" 2017 255
    "tl102" 2015 296
    "tl102" 2016 237
    "tl102" 2017 236
    end
    I want to make a graph of multiple countries (just some countries, not all), so I create a local list and write commands like this
    Code:
    local list "a123 as433 te398 cd923"
    local j=0
    foreach i of local list {
        local j=`j'+1
        local graphs `graphs' (line data year if id == "`i'", graphregion(fcolor(gs16)) legend(label(`j' "`i'")) ytitle("Data") xtitle("Year"))
        }
    graph twoway `graphs'
    Now I want to change the legend to show countries' name instead of "id". Could you give me a hint to do that without creating a new variable for country name (although I know name of country for each id)?

  • #2
    I found my own way. if anyone have better suggestion please tell me
    Code:
     
     local list "a123 as433 te398 cd923" local country "ctry1 ctry2 ctry3 ctry4" local j=0 foreach i of local list {     local j=`j'+1     local legend: word `j' of `country'     local graphs `graphs' (line data year if id == "`i'", graphregion(fcolor(gs16)) legend(label(`j' "`legend'")) ytitle("Data") xtitle("Year"))     } graph twoway `graphs'

    Comment

    Working...
    X