Announcement

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

  • Legend format with 2 equal columns

    Dear All,

    I am puzzled and confused as to how Stata decides on the width of the legend columns when their number is fixed, as in the following example.


    Click image for larger version

Name:	legend2cols_auto.png
Views:	1
Size:	84.0 KB
ID:	1565625




    Produced by the following code:

    Code:
    clear
    sysuse auto
    label variable length "Length in inches from bumper to bumper"
    label variable price "Market reference price at beginning of ref. period"
    twoway scatter weight length price mpg price, legend(cols(2))
    I can't understand:
    1. what makes the columns to be of unequal widths? (in my real world example the difference is more dramatic) and
    2. why the text of keys overflows out of the legend or into the next column?
    The manual is silent about the first problem, and mentions the second one specifically in the final remarks "Problems arising with or because of legends", citing imperfections in font measurement. Is this unavoidable?

    Is there any way to auto-arrange the legend so that it looks nice? Meaning no overlaps of text, no spill-overs outside and other reasonable expectations. Simply making the font size responsive to the text size would give it a much better appearance. Alternatively, automatic trancation with an ellipsis at the end of the string would also be useful.

    Clearly, changing the order of keys makes the picture nice again:
    Code:
    twoway scatter weight length price mpg price, legend(cols(2) order(1 2 4 3))
    Click image for larger version

Name:	legend2cols_auto2.png
Views:	1
Size:	83.6 KB
ID:	1565627

    It is possible to find such small adjustments almost in all cases, but that requires a human to look at the chart and invent a solution. I am looking for something more robust and automatic.

    PS: this is very reminiscent of this topic here: https://www.statalist.org/forums/for...or-legend-keys but not calling for wrapping the texts.

    Thank you, Sergiy
    Attached Files

  • #2
    Here is one way, using Ben Jann's -valuesof-:

    Code:
    clear
    
    sysuse auto
    label variable length "Length in inches from bumper to bumper"
    label variable price "Market reference price at beginning of ref. period"
    local myvar  weight length price mpg
    
    tempvar length  key group
    gen `length' = .
    gen `key' = .
    local i = 1
    qui {
        foreach var in `myvar' {
            local v : variable label `var'
            local l :  strlen local v
            replace `length'  =  `l' in `i'
            replace `key' = `i' in `i'
            local ++i
        }
    }
    egen `group' = fill(1 1 2 2)
    sort `group' `length'
    valuesof `key'
    local myorder = r(values)
    
    twoway scatter `myvar' price, legend(cols(2) order(`myorder')) scheme(s2color)

    Comment

    Working...
    X