Announcement

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

  • Creating PNG images Stata via Ghost Script

    Colleagues,

    I'm trying to follow Friedrich Huebler advice on generating PNG graphics with use of the GhostScript. I have the modest code (below), which generates the attached picture. The generated graph appears to have very wide white margins. I reckon that this may be mostly the question of GhostScript settings, nevertheless I decided to ask the question here as I would expect that some of you implemented Heubler's advice and work out the required GhostScript settings.



    Code:
    /* == AntiAliasing Example  == */
    
    // Load some data
    sysuse tsline2, clear
    tsset day
        
    // Set options for PostScript export
    graph set ps pagesize custom
    graph set ps pagewidth 5
    graph set ps pageheight 4
    graph set ps tmargin 0
    graph set ps lmargin 0
    graph set ps logo off
    graph set ps fontface Helvetica
    
    // Draw graph and export to PostScript file
    tsline calories, ttick(28nov2002 25dec2002, tpos(in)) ///
        ttext(3470 28nov2002 "thanks" 3470 25dec2002 "x-mas", orient(vert))
    graph export "line.ps", replace
    
    // Convert PostScript file to PNG format
    #delimit ;
    shell  "C:\gs9.15\bin\gswin64c.exe"
    -dSAFER -dBATCH -dNOPAUSE
    -r100 -g500x400 -sDEVICE=png16m
    -dGraphicsAlphaBits=4 -dTextAlphaBits=4
    -sOutputFile="line.png" "line.ps";
    Kind regards,
    Konrad
    Version: Stata/IC 13.1

  • #2
    This doesn't answer your question, but are you aware that you can directly -graph export- to .png format in Stata?

    Comment


    • #3
      Is there a reason why you need to export as .ps to begin with? More recent (I dunno Stata 11? 12? certainly 13) can export directly to .png. Oh, and your picture doesn't show up, at least not in my browser (Chrome under Windows 7).

      Comment


      • #4
        Originally posted by Clyde Schechter View Post
        This doesn't answer your question, but are you aware that you can directly -graph export- to .png format in Stata?
        Yes, I'm following Huebler's advice in order to get the PNG files with better anti-aliasing than provided by Stata's native PNG export mechanism.

        Originally posted by ben earnhart View Post
        Oh, and your picture doesn't show up, at least not in my browser (Chrome under Windows 7).
        It happened in past, it shows on my browser so I'm guessing that that's the usual issue with the updates.

        Kind regards,
        Konrad
        Version: Stata/IC 13.1

        Comment


        • #5
          Dear Konrad,

          The standard Stata PNG export facility is nice and useful but the resolution and the graphic elements formatting is 'as is', which is fine when it suits your needs.

          If you need 'more', the Ghostscript solution, recommended by Friedrich Huebler, will give the Stata user full control of how the graphic elements and text will appear in the final PNG file.
          I use it every day to create publication quality graphics where the largest benefit really is the ability to create (very) large PNG images (e.g. 1000x800 pixels), which is useful for high resolution printing or PDF's (because these large graphics are scaled down to a smaller size and thus will print as high resolution graphics).

          You are right, there are some subtleties to observe with how Stata controls the graphic image size and the formatting of its graphic elements (e.g. lines, text) and how the image will look after conversion to the PNG format using Ghostscript. Two issues you have always to keep in mind:

          1 The x,y setting of the Stata graph that has to be 'symmetrical' with the setting PostScript export pagewidth and pageheight settings, like:
          graph set ps mag 100
          graph set ps pagewidth 5
          graph set ps pageheight 4
          and then for the graph command: xsize(5) ysize(4)

          2 The -g setting in the Ghostscript syntax, to control the pixel width and height of the PNG file, has to be 'symmetrical' with the setting PostScript export settings, like:
          -g500x400

          - Note that to produce larger images you have to multiply the default setting the PostScript export of mag, and the setting of pagewidth and pageheight by the same factor, e.g. 3, as well as for the Ghostscript syntax, like:
          graph set ps mag 300
          graph set ps pagewidth 15
          graph set ps pageheight 12
          and for the Ghostscript syntax to control the pixel width and height of the PNG file:
          -g1500x1200

          But, do note that the maximum setting of pagewidth and pageheight of the PostScript export is 20, in any proportion between them, like:
          graph set ps pagewidth 20
          graph set ps pageheight 16
          In this set up you NEED NOT to change the graph command: xsize(5) ysize(4)!
          Actually, as long as you keep the proportions the same you could multiply them too, like: xsize(20) ysize(16), but that serves no purpose at all for conversion to the PNG format using Ghostscript.

          - Note that sometimes, for some reason, you can play with the Ghostscript syntax to control the pixel width and height of the PNG file to fine tune your result, like : -g1580x1230. This would not change the conversion to the PNG format but only decreases or increases the image at the right or bottom side.

          ***********************************************
          Now, to answer your question: you can control the margins using the xsize and xsize option of Stata's graphic commands, like:

          tsline calories, ttick(28nov2002 25dec2002, tpos(in)) ///
          ttext(3470 28nov2002 "thanks" 3470 25dec2002 "x-mas", orient(vert)) ///
          xsize(5) ysize(4)

          but, you also have a text string issue at the right side of your graph, which is easily solved by using the graphregion option of Stata's graphic commands, like:

          tsline calories, ttick(28nov2002 25dec2002, tpos(in)) ///
          ttext(3470 28nov2002 "thanks" 3470 25dec2002 "x-mas", orient(vert)) ///
          graphregion(margin(l-0 r+4 b-0 t-0)) xsize(5) ysize(4)

          After running this changed tsline command and your Ghostscript syntax the PNG image is just fine:

          Click image for larger version

Name:	line.png
Views:	1
Size:	26.4 KB
ID:	426327


          Actually, for optimal formatting of the graphic elements the PNG file, e.g. for publication purposes, the syntax for this is:

          * SYNTAX STARTS HERE
          * Set options for PostScript export
          graph set ps pagesize custom
          graph set ps mag 300
          graph set ps pagewidth 15
          graph set ps pageheight 12
          graph set ps tmargin 0
          graph set ps lmargin 0
          graph set ps logo off
          graph set ps fontface Helvetica //

          * Create the graph & ps file
          tsline calories, ttick(28nov2002 25dec2002, tpos(in)) ///
          ttext(3470 28nov2002 "thanks" 3470 25dec2002 "x-mas", orient(vert)) ///
          graphregion(fcolor(white) ilcolor(white) lcolor(white) margin(l-0 r+4 b-0 t-0)) xsize(5) ysize(4) ///
          xscale(lwidth(thick) noextend) ///
          xlabel(, tlwidth(thick) labsize(*1) nogrid) ///
          yscale(lwidth(thick) noextend) ///
          ylabel(, angle(0) tlwidth(thick) labsize(*1.1) nogrid) ///
          ytitle(, size(large) margin(l-1 r-0 b t)) ///
          xtitle(, size(*1.2) margin(l r+0 b-2 t+2))
          graph export "c:\linePub.ps", replace

          * Create the PNG file
          #delimit ;
          shell "C:\gs9.15\bin\gswin64c.exe" // or any other path
          -dSAFER -dBATCH -dNOPAUSE
          -r100 -g1500x1200 -sDEVICE=png16m
          -dGraphicsAlphaBits=4 -dTextAlphaBits=4
          -sOutputFile="c:\linePub.png" "c:\linePub.ps";
          #delimit cr
          * SYNTAX ENDS HERE

          Your result should be (the image file itself is much larger):
          Click image for larger version

Name:	linePub.png
Views:	2
Size:	78.8 KB
ID:	426330

          Best regards,
          Eric Melse


          Attached Files
          http://publicationslist.org/eric.melse

          Comment


          • #6
            Eric,

            thanks very much for getting back to me and the comprehensive answer. I was experimenting with this code and at the end changes xsize() and ysize() as well as the PostScript settings, as I couldn't achieve what I wanted, which is chart with no white margins, without those settings.

            Code:
               
            (...) chart definition (...)
            xsize(11) ysize(8) ///
                name(chart, replace)
                
            /* -- Chart export mechanism to PNG -- */
            
            // Set options for PostScript export
            graph set ps pagesize custom
            graph set ps pagewidth 11
            graph set ps pageheight 8
            graph set ps tmargin 0
            graph set ps lmargin 0
            graph set ps logo off
            graph set ps fontface Helvetica
            
            // Graph export
            graph export "chart.ps", replace
            #delimit ;
            shell  "C:\gs9.15\bin\gswin64c.exe"
            -dSAFER -dBATCH -dNOPAUSE
            -r100 -g1100x800 -sDEVICE=png16m
            -dGraphicsAlphaBits=4 -dTextAlphaBits=4
            -sOutputFile="chart.png" "chart.ps";
            Kind regards,
            Konrad
            Version: Stata/IC 13.1

            Comment


            • #7
              Originally posted by ericmelse View Post
              * Create the PNG file
              #delimit ;
              shell "C:\gs9.15\bin\gswin64c.exe" // or any other path
              -dSAFER -dBATCH -dNOPAUSE
              -r100 -g1500x1200 -sDEVICE=png16m
              -dGraphicsAlphaBits=4 -dTextAlphaBits=4
              -sOutputFile="c:\linePub.png" "c:\linePub.ps";
              #delimit cr
              * SYNTAX ENDS HERE
              Eric,

              Once again, thanks for your comments. Concerning the last bit of code, I was wondering if you do something to clean up after the export. Ideally I would like to move the exported graphs to ./Graphs/Export (or delete them) and the ps file to ./Graph/Stata. I was trying to run the shell command below, experimenting with the sleep #, but I couldn't get it to work.

              Code:
              // Clean
              local wd `c(pwd)'
              !move "exported_graph.png" "`c(pwd)'\Graphs\Exported" /-Y
              rm "exported_graph.ps"
              Alternatively, I can always provide paths but I would like to do as much of it automatically as possible, so I don't have to edit the code at each instance.
              Kind regards,
              Konrad
              Version: Stata/IC 13.1

              Comment


              • #8
                If possible, I would like to ask one more question: Can I make the white background transparent when saving images?
                Kind regards,
                Konrad
                Version: Stata/IC 13.1

                Comment


                • #9
                  Dear Konrad,

                  There is a Stata module <mvfiles> to 'move around' files on your system, created by Lars Angquist from Sweden: https://ideas.repec.org/c/boc/bocode/s457628.html
                  Just use:

                  ssc install mvfiles
                  help mvfiles

                  Your code would then be like, I suppose:
                  mvfiles , infolder(`c(pwd)') outfolder(`c(pwd)'\Graphs\Exported) match(exported_graph.png) erase
                  http://publicationslist.org/eric.melse

                  Comment


                  • #10
                    Dear Konrad,

                    Transparent colors in Stata? Well, that is a painful subject to discuss.
                    Stata does not provide that option for background (fill) colors or any other graphic objects.
                    I wrote about that to Stata Corp. some time ago, and made some comments about it elsewhere.
                    What we need here is "alpha blending" functionality in the graphics engine and that is not provided by Stata Corp.
                    Many Stata users want it, but, Stata Corp. explained to me that for cross platform compatibility reasons this is not possible.
                    Although I sympathise with that policy, I also think that for graphic capabilities it would be perfectly possible to implement "alpha blending" functionality only in the Windows and Apple versions.
                    I mean, suppose that you run some Stata syntax on very very very large datasets in Unix, the analysts most certainly could process the result set of data on a Windows or Apple system should they need transparency.
                    There are ample reasons to use transparency for visual analytics.

                    So, if you really need a transparent background you have to manually process the PNG file in a graphics editor.
                    E.g. when you use Photoshop, you could a transparency filter, like the one from Power Retouche: http://www.powerretouche.com/index.htm
                    Then you simply 'process' the background fill color into a 'transparent color' and save it again as another PNG file.
                    With my example the result is:
                    Click image for larger version

Name:	ExampleTransparantBackground.png
Views:	1
Size:	92.7 KB
ID:	437667
                    Attached Files
                    http://publicationslist.org/eric.melse

                    Comment


                    • #11
                      Eric,

                      Thank you very much for the useful comments. I agree with your points concerning cross platform compatibility. I'm thinking that on Mac, I can address the need to move the files with use of the Automator. So I'll use the mvfiles on Windows.
                      Kind regards,
                      Konrad
                      Version: Stata/IC 13.1

                      Comment


                      • #12
                        Hi everyone,

                        I hope you're doing well. I'm currently working on generating high-resolution figures for U.S. states using Stata. The figures are named, for example, "state_49." I've written a Stata script to combine these individual state figures into one composite figure and export it in both regular and high resolutions.

                        Here's the code I'm using:


                        Code:
                        * Generate list of file names using a loop
                        local file_list ""
                        foreach i in 2 3 4 6 8 9 10 11 12 13 14 15 16 18 19 20 22 24 {
                            local file_name state_`i'.gph
                            local file_list "`file_list' `file_name'"
                        }
                        ********************************************************
                        * Combine the graphs
                        grc1leg  `file_list', col(3)  graphregion(color(white)) ///
                         imargin(0 0 0 0) ///
                        saving(state_all_1, replace) ///
                        legendfrom(state_2.gph) //
                        ********************************************************
                        graph display, ysize(6) xsize(4)
                        graph export state_all_1.png, replace // Works but with low resolution
                        * Generate HD picture
                        // Set options for PostScript export
                        graph set ps pagesize a4
                        graph set ps tmargin 0
                        graph set ps lmargin 0
                        
                        // Graph export
                        graph export "state_all_1.ps", replace
                        #delimit ;
                        shell  "C:\Program Files\gs\gs10.02.1\bin\gswin64c.exe"
                        -dSAFER -dBATCH -dNOPAUSE
                        -r100 -g1240x1754 -sDEVICE=png16m
                        -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -sPAPERSIZE=a4
                        -sOutputFile="state_all_1_HD.png" "state_all_1.ps";
                        While the code works, I'm encountering an issue with the high-resolution figure (state_all_1_HD.png). The figure is shifted down, leaving a large white margin at the top, and the bottom part is getting cropped.

                        I would greatly appreciate your insights into how I can modify the code to address this problem and ensure the figure is correctly aligned and cropped. Thank you in advance for your help!

                        Best regards,
                        Serge
                        +61457871540

                        Low resolution, but correct (state_all_1.png)

                        Click image for larger version

Name:	state_all_1.png
Views:	1
Size:	383.7 KB
ID:	1739800

                        High resolution, but incorrect (state_all_1_HD.png)
                        Click image for larger version

Name:	state_all_1_HD.png
Views:	1
Size:	183.0 KB
ID:	1739801
                        Kind regards,
                        Sergey Alexeev | ​The University of Sydney
                        https://alexeev.pw/

                        Comment

                        Working...
                        X