Announcement

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

  • Create multiple graphs by group

    Dear Statalist,

    I am trying to generate and export twoway scatter plot by GroupID (one plot for one GroupID). My x-axis is cost data and my y-axis is date data. I want each graph only contains data correspond to the GroupID.

    My current code is:
    Code:
     
      sum GroupID, meanonly
      global groupmax `r(max)'
      forvalues i = 1/$groupmax {
        twoway scatter Cost DateYM, by(GroupID)
        graph export "graph/GroupIDplot'", replace
       }
    I got the following error
    output file suffix not recognized
    Specify correct suffix or specify as() option.
    Not sure what is wrong with my code and not sure if my code can generate graphs that I want. Any comment will be appreciated.

    Thanks!

  • #2
    There seems to be some confusion underlying the code in #1. On the one hand, a -forvalues- loop is iterating i over values of i between 1 and the maximum value of variable GroupID. On the other hand, within the loop body there is no mention of `i', and, in fact, the key command, -twoway scatter Cost DateYM, by(GroupID)- creates a single graph with multiple panels, one panel per value of GroupID. So that same command gets repeatedly executed, and, were it not for the incorrect syntax in the -graph export- command, the same file would be overwritten each time.

    The error message being given arises because the filename specified is not a legal graphics file name. It should be something like GroupIDPlot.png, or GroupIDPlot.emf, or GroupIDPlot.jpg, etc. I don't know what kind of graphics file is wanted. In the rest of this post, I will illustrate the code assuming a png file is to be created--O.P. can modify according to the actually desired file type.

    I cannot tell exactly what is wanted here. If it is a separate file containing a graph of the data for each value of GroupID, then the code should look more like this:
    Code:
    levelsof GroupID, local(groups)
    foreach g of local groups {
        twoway scatter Cost DateYM if GroupID == `g'
        graph export "graph/GroupIDPlot_`g'.png", replace
    }
    If however, O.P. wants to have a single graph with a panel for each GroupID, then no loop is necessary. In that case:
    Code:
    twoway scatter Cost DateYM, by(GroupID)
    graph export "graph/GroupIDPlot_all.png", replace
    will do it.
    Last edited by Clyde Schechter; 23 Aug 2022, 14:36.

    Comment

    Working...
    X