Announcement

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

  • Applying legend from value labels of different categorical variables in a loop

    Dear all,

    Stata version: 14.1, updated.


    I have done some google search with this problem and could not find anything but I am sure it has been discussed before. If anyone can direct me to a relevant link or provide me a solution for the problem below, it will be great.

    Problem: I am trying to create Kaplan-Meier graphs on several categorical variables (coded 0/1) in a loop. How can I make the legends to automatically extract the value labels of the categorical variables and apply in a loop. The codes are below and the red fonts require attention. Thanks in advance.

    Code:
    gr drop _all
    loc m=1
    
    foreach var of varlist base help drug rand gender past trt {
        sts graph,by(`var')  ///
        ylab(0.5 (.1) 1, nogrid ang(hor)) xlab(0(10)80) xtitle(" " "Survival weeks") ///
        legend(order(1 "Legen group-1 of 1st var" 2 "Legend group-2 of 1st var ") region(col(white))) ///
        plot1opts(lpatt(solid) col(black)) ///
        plot2opts(lpatt(shortdash) col(black)) ///
        graphregion(col(white)) title("")
    gr copy x`i',replace
    loc ++m
    }
    Last edited by Roman Mostazir; 22 Aug 2016, 16:43. Reason: Added variable codes
    Roman

  • #2
    Just to provide a little more information, if helpful, with the codes above, legends are displayed for each variable but they are not as I want them. For example for the variable 'rand', the legend appears as:
    Code:
     " varname = value label" i.e. rand = Control rand=Treatment.
    Roman

    Comment


    • #3
      I think that is a valuable question. Two years have past, there is still no answer.
      Last edited by Chen Samulsion; 10 Dec 2018, 00:34.

      Comment


      • #4
        I don't understand that question, as sts graph already uses those labels automatically.
        ---------------------------------
        Maarten L. Buis
        University of Konstanz
        Department of history and sociology
        box 40
        78457 Konstanz
        Germany
        http://www.maartenbuis.nl
        ---------------------------------

        Comment


        • #5
          Edit:
          I understand the question to the annoying behavior of -sts graph- to display: > varname = value label< and not just >value label< in the legend.
          The following code can be a part of the solution.
          Edit off.

          a basic solution could be something like:

          Code:
          clear
          
          sysuse cancer
          
          gen loopvar2 = drug
          
          label define drug 1 "Placebo" 2 "Drug 1" 3 "Drug 2", modify
          label define loopvar2 1 "Class 1" 2 "Class 2" 3 "Class 3", modify
          
          label val drug drug
          label val loopvar2 loopvar2
          
          foreach v of varlist drug loopvar2 {
              display "`:label (`v') 1'"
              sts graph, by(`v') ///
              legend( order( 1 "`:label (`v') 1'"  2 "`:label (`v') 2 '" 3 "`:label (`v') 3'") )
              }
          although there would be a lot of caveats to take into account when using a system like the above in a loop.
          If the variables do not contain the same values, it will mess the system up.
          Use with caution
          Last edited by Dennis Lund Hansen; 10 Dec 2018, 01:24. Reason: adding description of the interpretation of the question.

          Comment


          • #6
            Dear Dennis Lund Hansen, thank you very much for the discussion. I mean another case which I encountered these days. Suppose I have several dummies variables that share common label pattern, for example price1 is labelled as "repair 1", price 2 is labelled as "repair 2" and so on. Just as Maarten Buis said, when we graph a twoway plot (or any Stata plot) programme uses those labels automatically in legend option. But now I go further to add some texts to every labels. For example, for price1, I want its legend be "repair 1 (2.9%)", for price2, I want its legend be "repair 2 (11.59%)", and so on. If we don't add the separate texts manually, I wonder if there be an automated workaround. Thank you.
            Code:
            sysuse auto
            tabulate rep78
            label define rep78 1 "repair 1" 2 "repair 2" 3 "repair 3" 4 "repair 4" 5 "repair 5"
            label values rep78 rep78
            separate price, by(rep78) veryshortlabel
            twoway dot price1-price5 rep78, sort xlabel(, valuelabel) legend(posi(6) row(2) order(1 "repair 1 (2.9%)" 2 "repair 2 (11.59%)" 3 "repair 3 (43.48%)" 4 "repair 4 (26.09%)" 5 "repair 5 (15.94%)"))

            Comment


            • #7
              Chen Samulsion It's the other way round. Decide that you want do something -- e.g. add to category value labels the percent of each category -- and it can be automated. The extra syntax to do what else you want is .(vacuously but truly) the rest of Stata.

              Community-contributed commands often arise when someone got fed up with typing the same stuff again and again. You cite separate, which is long since an official command, but that is how it arose too.

              Comment


              • #8
                I can see, that Cox has already given a general answer, and I will only add, that I can see a way to automate the percentage information, but I can not see an easy way to automatically convey that information into the legend.
                You can use a local - as I suggest below, to semiautomate it, but it will require some maintanence if you copy it to a new do-fil and dataset.

                Code:
                sysuse auto, clear
                tabulate rep78
                label define rep78 1 "repair 1" 2 "repair 2" 3 "repair 3" 4 "repair 4" 5 "repair 5"
                label values rep78 rep78
                separate price, by(rep78) veryshortlabel
                
                twoway dot price1-price5 rep78, ///
                    sort xlabel(, valuelabel) ///
                    legend(posi(6) row(2)    ///
                    order(1 "repair 1 (2.9%)" ///
                    2 "repair 2 (11.59%)" ///
                    3 "repair 3 (43.48%)" ///
                    4 "repair 4 (26.09%)" ///
                    5 "repair 5 (15.94%)"))
                    
                * suggestion:
                local order_txt ""
                
                levelsof rep78, local(levelsrep)
                foreach l of local levelsrep {
                        tempvar var`l'
                        gen `var`l'' = (rep78== `l') if !missing(rep78)
                        ci prop `var`l'' 
                        local prop`l' = strofreal(`= `r(proportion)'*100', "%9.2f")
                        local order_txt `" `order_txt' `l' "repair `l' (`prop`l''%)" "'
                        }
                        
                                            
                twoway dot price1-price5 rep78, ///
                    sort xlabel(, valuelabel) ///
                    legend(posi(6) row(2)    ///
                    order(    `order_txt' ))

                Comment


                • #9
                  Nick Cox Dennis Lund Hansen, thank you so much. Productivity hacks from lazy and successful people.

                  Comment


                  • #10
                    Chen Samulsion #3 and Dennis Lund Hansen #5, I should have closed this thread as soon as I resolved the problem as per the forum rules and my sincere appology for not doing it. Getting back to the old files showed that I did the following to resolve the matter (assuming dummy variables are coded as 0, 1):

                    Code:
                    gr drop _all
                    loc m=1
                    foreach var of varlist rand gender pastmde {
                        
                        forval j=0/1 {
                        loc t`j': lab (`var') `j'
                        }
                        
                    sts graph, by(`var')  ///
                        ylab(0.5 (.1) 1, nogrid ang(hor)) xlab(0(10)80) xtitle(" " "Survival weeks") ///
                        legend(order(1 "`t0'" 2 "`t1'") region(col(white))) ///
                        plot1opts(lpatt(solid) col(black)) ///
                        plot2opts(lpatt(shortdash) col(black)) ///
                        graphregion(col(white)) ti("`:var lab `var''", col(black))
                        gr copy x`m', replace
                        loc ++m
                    }
                    
                    gr combine x1 x2 x3
                    Roman

                    Comment

                    Working...
                    X