Announcement

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

  • Problem with using macros in file names, exporting graphs

    Colleagues,

    I have an elaborate graphic command that I use to derive charts. I'm currently trying to add two extra lines to the syntax that would save the graphs in desired folder but somehow the graph save and graph export commands do not appear to work.

    Code:
    {/*---------------- Chart  -------------------------*/
    
    /* Set colour scheme */
    set scheme Burd11
    
    * Make snapshot for the backup.
    snapshot save, label("Backup before chart")
    local recsnap = r(snapshot)
    
    *Start doing the chart.    
    local timevar hsr9_
    local varlabel "Text"
    local yaxtitle "Unit"
    local xaxtitle "Year or something like that"
    
    reshape long `timevar', i(observation) j(time) string
    
    * Change syntax for the time variable.
    gen date = yearly(time, "Y")
    format %tyCCYY date
    
    * generate group for the time series.
    generate group = abcgroup== "Case ABC"
    
    * Define label for the variable.
    label define groups 0 "Rest" 1 "Case ABC"
    label values group groups
    
    * Define time series data.
    capture : xtset group date
    collapse (mean) `timevar', by(group date)
    xtset group date
    
    * Draw time series graph.
    label variable `timevar' "`varlabel'"
    local charttitle : var label `timevar'
    
    xtline `timevar', overlay ///
        plot1(lwidth(medthick) lpattern(shortdash)) ///
        plot2(lwidth(medthick) lpattern(solid)) ///
        title("`charttitle'", size(medsmall) position(12) margin(vsmall)) ///
        subtitle("{it: Text}", ///
                size(small) position(12)) ///
        caption("{it: Data Source: source.}", ///
                size(vsmall)) ///
        legend( rows(1) size(vsmall) position(6) rowgap(.5) ///
        region(fcolor(ltbluishgray) lcolor(navy)))  ///
        ytitle("`yaxtitle'", size(vsmall)) ///
        xtitle("`xaxtitle'", size(vsmall)) ///
        ylabel(, labsize(vsmall) ) ///
        xlabel(#8, labsize(vsmall) ) ///
        name(timechart_`timevar', replace)        
    
    * Restore snapshot.
    snapshot restore `recsnap'
    
    * Save graph.  
    graph save timechart_`timevar' ///
        "C:\_path_\Graphs\Stata\timechart_`timevar'.gph", ///
        replace
    
        * Export graph.  
    graph save timechart_`timevar' ///
        "C:\_path_\Graphs\Exports\timechart_`timevar'.png", ///
        replace
    
    
    /*------------------------------------------------------------------*/}
    Kind regards,
    Konrad
    Version: Stata/IC 13.1

  • #2
    Konrad,

    You don't indicate what "does not appear to work" means, so it's hard to say what is wrong with the first graph save command. In order to export a graph to a PNG file, you need to use graph export.

    Regards,
    Joe

    Comment


    • #3
      Unless you provide a bit more information I don't think we can do more than speculate. What exactly is not working? Do you receive an error message? Is the local empty? Do the commands work the first time but afterwards they stop working? You would probably need to put a loop around if I am not mistaken since "graph save" and "graph export" only work on the last graph in memory...

      Comment


      • #4
        Your problem may relate to how -snapshot- works. If -snapshot restore- restore old graphs, you will lose all your work.
        Try re-ordering the commands so that you save before restoring:
        Code:
        /*---------------- Chart  -------------------------*/
        
        /* Set colour scheme */
        
        set scheme Burd11
        
        * Make snapshot for the backup.
        
        snapshot save, label("Backup before chart")
        
        local recsnap = r(snapshot)
        
        <snip>
        
        
        xtline `timevar', overlay ///
        
            plot1(lwidth(medthick) lpattern(shortdash)) ///
        
            plot2(lwidth(medthick) lpattern(solid)) ///
        
            title("`charttitle'", size(medsmall) position(12) margin(vsmall)) ///
        
            subtitle("{it: Text}", ///
        
                    size(small) position(12)) ///
        
            caption("{it: Data Source: source.}", ///
        
                    size(vsmall)) ///
        
            legend( rows(1) size(vsmall) position(6) rowgap(.5) ///
        
            region(fcolor(ltbluishgray) lcolor(navy)))  ///
        
            ytitle("`yaxtitle'", size(vsmall)) ///
        
            xtitle("`xaxtitle'", size(vsmall)) ///
        
            ylabel(, labsize(vsmall) ) ///
        
            xlabel(#8, labsize(vsmall) ) ///
        
            name(timechart_`timevar', replace)        
        
        * Save graph.  
        
        graph save timechart_`timevar' ///
        
            "C:\_path_\Graphs\Stata\timechart_`timevar'.gph", ///
        
            replace
        
            * Export graph.  
        
        graph save timechart_`timevar' ///
        
            "C:\_path_\Graphs\Exports\timechart_`timevar'.png", ///
        
            replace
        
        * Restore snapshot.
        
        snapshot restore `recsnap'
        
        /*------------------------------------------------------------------*/}

        Comment


        • #5
          Paul,

          thanks for the suggestion. I quickly tried adding:
          Code:
           graph save      timechart_`timevar' "C:\timechart_`timevar'.gph"
          Before restoring snapshot but got an error message: file C:\timechart_frdel_fire_rate.gph could not be opened.
          Kind regards,
          Konrad
          Version: Stata/IC 13.1

          Comment


          • #6
            Do you have write permission to C:?

            Comment


            • #7
              Yes, I have.
              Kind regards,
              Konrad
              Version: Stata/IC 13.1

              Comment


              • #8
                Progress here is slow.

                One reason is perhaps that you haven't yet given us a reproducible example. For example, perhaps something upstream of your code is having an effect. Come back with a self-contained example based on data readable into anyone's Stata.

                Another reason is that you haven't addressed Martin Bresslein's questions so far as I can see.

                Comment


                • #9
                  Thanks all the replies, reproducible code is below:

                  Code:
                  sysuse auto
                  foreach var of varlist  price mpg {
                      graph bar `var', name(bar_`var', replace)
                      graph save bar_`var' "c:\bar_`var'"
                  }
                  The output from the the command, together with the error message:

                  Code:
                  . sysuse auto
                  (1978 Automobile Data)
                  
                  . foreach var of varlist  price mpg {
                    2.         graph bar `var', name(bar_`var', replace)
                    3.         graph save bar_`var' "c:\bar_`var'"
                    4. }
                  file c:\bar_price.gph could not be opened
                  r(603);
                  
                  end of do-file
                  Kind regards,
                  Konrad
                  Version: Stata/IC 13.1

                  Comment


                  • #10
                    This assumes that the user has a c: and that backslashes are acceptable in filepaths, which restricts possible users to those under Windows.

                    Nevertheless I can report that the code works for me. (c: strikes me as an odd place to put graphs, but that's quite different.)

                    Some problems in which local macros are used turn out to hinge on the fact that the user issued some statements interactively and the others from another place. In your case, you leave a clue that the commands are issued from a single do-file, so that's not it.

                    I am left only with my previous idea, which is that something about your
                    c: inhibits saving. Try some other location.

                    Comment


                    • #11
                      Thanks, interesting suggestion as I keep on saving files on the C drive. Maybe there are some permission settings that prevent Stata from saving directly to the C: drive. C drive is only used here as an example, in my daily work I would use a proper path and I was getting the same error when trying to save in my user path. Out of curiosity would it be possible to use the current working directory. In particular, I would like to enrich the command with:
                      Code:
                      local dir `c(pwd)'
                      in order to use:
                      Code:
                      graph save bar_`var' "`dir'bar_`var'"
                      Kind regards,
                      Konrad
                      Version: Stata/IC 13.1

                      Comment


                      • #12
                        Did you try it? I'd advise a separator. Stata understands forward slashes / even under Windows.

                        Comment


                        • #13
                          If you want to save to the working directory, you can just omit the path altogether.

                          Code:
                          sysuse auto
                          
                          foreach var of varlist price mpg {
                              graph bar `var', name(bar_`var', replace)
                              graph save bar_`var' "bar_`var'" , replace
                          }
                          If that works, then your problem has to do with writing to your C: directory.

                          Unless you're getting a sharing violation, if the file is open in another program or Stata window.

                          Mike

                          Comment


                          • #14
                            Mike is correct. Indeed Stata by default saves the current graph, so the graph name too is redundant.

                            Comment


                            • #15
                              Colleagues,

                              Thanks very much for your comments, it appears that it worked perfectly (results below). I would presume that, as suggested, the problem is with writing directly to the C: drive but then permission check (icacls) shows that I have every right to write to C:.

                              Code:
                              . foreach var of varlist price mpg {
                                2.         graph bar `var', name(bar_`var', replace)
                                3.         graph save bar_`var' "bar_`var'" , replace
                                4.         }
                              (note: file bar_price.gph not found)
                              (file bar_price.gph saved)
                              (note: file bar_mpg.gph not found)
                              (file bar_mpg.gph saved)
                              Kind regards,
                              Konrad
                              Version: Stata/IC 13.1

                              Comment

                              Working...
                              X