Announcement

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

  • Modify legend in twoway kernel density graph in a loop

    Dear Statalists,

    I am working on a loop aimed at plotting overlying kernel density plots for all the categories of some variables in my dataset. I managed to make it in this way:

    foreach var in v1 v2 v3 v4 {
    levelsof(`var'), local(levels`var')
    foreach l of local levels`var' {
    local call`var' `call`var'' (kdensity y if `var'==`l', bwidth(3))
    }
    twoway `call`var'', ytitle(Density) ylab(0(0.01)0.05, grid) graphregion(color(white)) xlabel(0(10)100, grid)
    }

    I have, however, two questions. First, do you think there are more efficient way to produce the same results? And second, I would like to modify the legend of my twoway kernel graph to have the labels of the variables' categories, do you have any suggestion on how to do it? Thanks!

  • #2
    See https://www.statalist.org/forums/for...lable-from-ssc

    Even if that command is not what you want, you might find that you can steal some of the code.

    Comment


    • #3
      Hi Nick, thank you for the suggestion, I didn't know about this command! I am trying to use it now, but I'm having a weird problem with the graphs mixing up different variables's categories kernel densities, as you can see in the attached picture.
      There shouldn't be any mistake in the code:

      foreach var in v1 v2 v3 {
      multidensity gen y if v4==0 & v5==1, by(`var') bw(3)
      multidensity super, graphregion(color(white)) xlabel(0(10)100, grid)
      graph export "graph.png", as(png)
      }

      and I've already tried to shut down Stata and restart it, but the problem remains. Do you have any suggestion? Thanks in advance!
      Attached Files

      Comment


      • #4
        You are trying to write to the same .png file each time around the loop.

        Comment


        • #5
          Sorry, immediately after writing I realized the mistake. Thank you very much again!

          Comment

          Working...
          X