Announcement

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

  • Inserting image in Stata graph

    Is there a way to insert/paste an image into a Stata graph from within the Stata environment? Let me explain what I need. I have written a program to read in some data, calculate some index numbers, and produce a set of graphs, which are then exported to other formats (TIF/EPS etc.). I need to insert an institutional logo/symbol into each graph. Currently this is being done outside Stata using a graphics editing software, working with the exported graphs. That of course adds a delay to the process, which it would be very desirable to avoid, since this is a repeated task with a tight deadline. So I was wondering if there is some way to automate this process from within Stata, e.g., using a command to insert an external graphic into a special field within the Stata graph (in its graph/plot region). I wonder if any other member has handled this type of task, and could offer some suggestion how to best achieve it? Thanks & regards.
    Last edited by Partho Sarkar; 23 Dec 2015, 09:50.

  • #2
    Partho:
    I don't think there is any direct method for doing this in Stata, but here are a few ideas for automating the process (that is, creating the overlayed images from a Stata do-file) that are similar to things I've done in the past:


    1) Use LaTeX or HTML to overlay the images.
    So, in this scenario you would input the graphic into the TeX or HTML file (you can program this from the Stata .do file using packages from SSC like -texdoc- or -weaver- which avoids going outside of Stata to finish this work) and use solutions for TeX or HTML to overlay the logo on top of your image.

    For images piped to Latex, here is a MWE:
    (alternately, you can use the TIKZ 'overlay' package to do this)
    (nb, You are able to run the command line part below as a part of your do-file by shelling out (see -help shell-))

    Code:
    ****************************begin latex example
    *--get texdoc from ssc
    cap which texdoc
    if _rc ssc install texdoc, replace
    *--get logo for example
    copy http://logonoid.com/images/stata-logo.png "logo.png", replace public
    
    *-- example data/graph
    sysuse auto, clear
    tw (scatter price mpg, mlabel(make)) (lfit price mpg), xsize(6) ysize(4)
    graph export "fig1.png", as(png) replace
    
    *-- use texdoc to make the latex file that will become the pdf image (and convert if necessary)
    texdoc init myexample.tex, replace
    
    tex  \documentclass{article}
    *tex \usepackage{auto-pst-pdf}
            ** might need for PS graphics
    tex \usepackage{graphicx}
    tex \usepackage[a4paper, landscape, margin=.5in]{geometry}
    tex \usepackage{psfrag}
    tex \usepackage{pstricks}
    
    tex \begin{document}
    tex \pagestyle{empty}
    
    tex \begin{postscript}
    tex \includegraphics[scale=.75]{fig1}
    tex  \rput(-1.5,9){\includegraphics[width=90pt]{logo}}
    tex \end{postscript}
    tex \end{document}
    texdoc close
    
    *-Compile this automatically from command line or use your latex software
    local fff "myexample" //put in loop if you have lots of files to compile
    if "`c(os)'" == "Windows"{
            !pdflatex --shell-escape  "`fff'.tex"  //I use mac, so I havent tested this line in Windows
      }
    if "`c(os)'" == "MacOSX" {
        cap rm "`fff'.pdf"
        !/usr/texbin/pdflatex --shell-escape   "`fff'.tex"  "`fff'"
        !/usr/texbin/pdflatex --shell-escape   "`fff'.tex"  "`fff'" //I like to compile twice to ensure it worked
        }        
    *-then add code to convert the pdf file if needed using ghostscript or something like: http://tex.stackexchange.com/questions/20883/how-to-convert-pdf-to-eps
    
    ****************************end latex example
    produces:
    Click image for larger version

Name:	ex1.png
Views:	1
Size:	108.5 KB
ID:	1321033



    For images piped to HTML you can use a one or more of html or css or javascript to easily overlay images, something like what is discussed here: http://stackoverflow.com/questions/5...-another-image
    and then you can integrate the HTML/CSS/whatever code similar to the process above but I'd advise using -weaver- (from SSC) for this approach (or write your own html/etc files using the -file- commands like -file write- ).




    2) Convert the image to HTML (using a program like GIMP, which can be automated) and use Stata to draw the logo.
    The method is less straightforward (I had lots of issues getting something like this to do what I wanted) and probably best illustrated with the example below from this page (the code at this URL is nested under a graph that includes a car as a background image, but since it's buried I'm pasting the code below for you) see: http://www.surveydesign.com.au/tipsgraphs.html

    Code:
    // Adding a picture as background to a graph
    
    //The above picture can be improved on, if required, by converting a picture
    //into html and then cleaning this file up in Stata.
    
    //The picture is first loaded into GIMP (free software program, this step can be automated) and then saved
    //as html (Remmember the larger the picture the more computer resources are
    //required and the longer it will take to process the code)
    
    clear all
    set more off
    set memory 900m
    
    program hex
    
      syntax varname , Newv(name)
    
        generate `newv'=((strpos("`=c(alpha)'",`varlist')-1)/2)+10
        replace `newv'=real(`varlist') if `newv'==9.5
    
    end
    
    //values that can be changed
    local divide=8     //sample size
    
    insheet using "c:/fast car.html", clear
    
    generate row=.
    replace row=1 if strpos(v1,"< TR>")
    replace row=sum(row)
    
    keep if strpos(v1, " < TD  BGCOLOR")
    
    split v1,p(#)
    split v12,p(>)
    keep row v121
    
    generate obs=_n
    
    bysort row (obs):gen col=_n
    
    rename v121 hex
    generate hex1=substr(hex,1,1)
    generate hex1a=substr(hex,2,1)
    
    generate hex2=substr(hex,3,1)
    generate hex2a=substr(hex,4,1)
    
    generate hex3=substr(hex,5,1)
    generate hex3a=substr(hex,6,1)
    
    hex hex1, newv(dec1)
    hex hex1a, newv(dec1a)
    
    hex hex2, newv(dec2)
    hex hex2a, newv(dec2a)
    
    hex hex3, newv(dec3)
    hex hex3a, newv(dec3a)
    
    generate dec1b=16*dec1+dec1a
    generate dec2b=16*dec2+dec2a
    generate dec3b=16*dec3+dec3a
    
    keep dec1b dec2b dec3b row col
    
    generate dec1c=floor(dec1b/`divide')*`divide'
    generate dec2c=floor(dec2b/`divide')*`divide'
    generate dec3c=floor(dec3b/`divide')*`divide'
    
    gen str20 color=char(34)+string(dec1c,"%3.0f")+" "+string(dec2c,"%3.0f") ///
    +" "+string(dec3c,"%3.0f")+char(34)
    
    egen group_col=group(color)
    
    compress
    save pict_graph, replace
    
    use pict_graph, clear
    quiet summarize col
    
    local size="*`=33/`r(max)''"     //marker size, can be adjusted
    
    levelsof color, local(a)
    
    merge 1:1 _n using  "C:\Program Files\stata11\ado\base/a/auto.dta"
    summarize length
    
    gen y=90+(((_N-_n+1)-90))/(_N/r(max))
    
    //scaling x axis picture data
    replace col=col/9
    
    local z=1
    
    foreach i of local a {
    
      if `z'==1 {
    local zz =  ///
    `"(scatter y col if group_col==`z',msymbol(square) mcolor(`i') msize(`size'))"'
    
        local z=2
       }
          else {
    local zz1 = ///
    `"(scatter y col if group_col==`z' ,msymbol(square) mcolor(`i') msize(`size'))"'
    
    local zz "`zz' `zz1'"
    local ++z
          }
    }
    
    twoway `zz'                                      ///
    (scatter  length mpg, mcolor(red) msize(large))  ///
    (lfit  length mpg)                               ///
    ,yscale( range(100 325))                         ///
    ytitle(Length ins.) xtitle(mpg)                  ///
    title(Mpg v Length) legend(off)
    
    exit


    3) Use a command line program to overlay and process the images.
    Use ImageMagick's (or a similar freeware command line tool) "composite" commands to automate overlaying the images.
    Here is an example and info on the syntax: http://www.imagemagick.org/script/composite.php

    Again, you can run this command line as a part of your do-file by shelling out (see -help shell-).



    HTH,
    Eric Booth
    [email protected]


    Last edited by eric_a_booth; 23 Dec 2015, 12:10.
    Eric A. Booth | Senior Director of Research | Far Harbor | Austin TX

    Comment


    • #3
      Thank yo so much, Eric, for your detailed & very helpful suggestions! I'll try these ideas out as soon as I can, and get back to you. I have some experience with outputting graphs into RTF files using Roger Newson's RTFUTIL, including shelling out to Windows, so should be able to work it out (might come back for more help!). One small wrinkle is that I currently work mostly on a Mac OsX, and Shellout doesn't seem to work there. But I can switch back to PC Windows for this.

      Comment


      • #4
        Partho:
        -shellout- (from SSC) is just a wrapper for the commands to open applications in Windows, but you can shell out yourself in Mac OS X or other OSs without it. Take a look at -help shell- to see that in Mac OS X you can run commands like these in your do-files:
        Code:
        shell open -a finder
        shell open myfile.pdf
        shell  open myfile.html
        and so on all work fine in Mac OS X.
        These are equivalent to the "!" commands in my examples, like:
        Code:
        ! open -a finder
        !  open  myfile.pdf
        !  open myfile.html
        and you can open/edit/etc files with specific applications with commands like:

        Code:
        ! open -a Preview  fig1.png
        in your do-files.
        Eric A. Booth | Senior Director of Research | Far Harbor | Austin TX

        Comment


        • #5
          Great- many thanks, Eric!

          Regards
          Partho S.

          Comment


          • #6
            Hello!

            Sorry to bump this very old thread, but I know forum admnis, everywhere in the world, like it when users go search for old threads and continue them if their argument is the same. There I am.

            My issue: I have become quite good at making maps with spmap by now, adding points, circles, labels, roadways instead of having just polygons and their colours. However, there is something I am missing that I seem unable to overcome on my own: adding a "background map". Because yes, spmap refers to some "background map" thingy in the Stata help, but I have no idea about what it is. Now, I would like to add some sort of background to my maps, for example the heightmap, that is a scale of grays indicating the altitude of terrain. Or even perhaps adding an orthophoto, with some strong degree of transparency to allow the information on the map to remain in the grasp of the viewer.

            I could not come up with a workable solution even after reading the answers above here, this is why I am writing Of course, what I want to do could be done, perhaps more easily, in programs like GIMP, but I'd like to do things the Stata way, you know!

            Thanks anyone willing to help.

            Comment


            • #7
              I think someday Stata might start adding ability to read image pixels only then we might be able to do all this natively. Will be nice to see this feature though

              Comment

              Working...
              X