Plot matplotlib on the Web











up vote
10
down vote

favorite
5












The following code will of course create a PNG named test and save it on the server:



from matplotlib.figure import Figure                         
from matplotlib.backends.backend_agg import FigureCanvasAgg

fig = Figure(figsize=[4,4])
ax = fig.add_axes([.1,.1,.8,.8])
ax.scatter([1,2], [3,4])
canvas = FigureCanvasAgg(fig)
canvas.print_figure("test.png")


Then to view the image in the browser, we have to go to example.com/test.png. This means we have to call the page with the Python code first to create the test.png file, then go to the PNG file. Is there a way to draw the PNG and output from the Python page that creates the image? Thanks!










share|improve this question


























    up vote
    10
    down vote

    favorite
    5












    The following code will of course create a PNG named test and save it on the server:



    from matplotlib.figure import Figure                         
    from matplotlib.backends.backend_agg import FigureCanvasAgg

    fig = Figure(figsize=[4,4])
    ax = fig.add_axes([.1,.1,.8,.8])
    ax.scatter([1,2], [3,4])
    canvas = FigureCanvasAgg(fig)
    canvas.print_figure("test.png")


    Then to view the image in the browser, we have to go to example.com/test.png. This means we have to call the page with the Python code first to create the test.png file, then go to the PNG file. Is there a way to draw the PNG and output from the Python page that creates the image? Thanks!










    share|improve this question
























      up vote
      10
      down vote

      favorite
      5









      up vote
      10
      down vote

      favorite
      5






      5





      The following code will of course create a PNG named test and save it on the server:



      from matplotlib.figure import Figure                         
      from matplotlib.backends.backend_agg import FigureCanvasAgg

      fig = Figure(figsize=[4,4])
      ax = fig.add_axes([.1,.1,.8,.8])
      ax.scatter([1,2], [3,4])
      canvas = FigureCanvasAgg(fig)
      canvas.print_figure("test.png")


      Then to view the image in the browser, we have to go to example.com/test.png. This means we have to call the page with the Python code first to create the test.png file, then go to the PNG file. Is there a way to draw the PNG and output from the Python page that creates the image? Thanks!










      share|improve this question













      The following code will of course create a PNG named test and save it on the server:



      from matplotlib.figure import Figure                         
      from matplotlib.backends.backend_agg import FigureCanvasAgg

      fig = Figure(figsize=[4,4])
      ax = fig.add_axes([.1,.1,.8,.8])
      ax.scatter([1,2], [3,4])
      canvas = FigureCanvasAgg(fig)
      canvas.print_figure("test.png")


      Then to view the image in the browser, we have to go to example.com/test.png. This means we have to call the page with the Python code first to create the test.png file, then go to the PNG file. Is there a way to draw the PNG and output from the Python page that creates the image? Thanks!







      python matplotlib






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 1 '11 at 15:11









      Jason Strimpel

      4,264114680




      4,264114680
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          20
          down vote



          accepted










          First you need a page to load a url from the webserver controller which generates the image:



          <img src="/matplot/makegraph?arg1=foo" />


          Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:



          import cStringIO
          from matplotlib.figure import Figure
          from matplotlib.backends.backend_agg import FigureCanvasAgg

          fig = Figure(figsize=[4,4])
          ax = fig.add_axes([.1,.1,.8,.8])
          ax.scatter([1,2], [3,4])
          canvas = FigureCanvasAgg(fig)

          # write image data to a string buffer and get the PNG image bytes
          buf = cStringIO.StringIO()
          canvas.print_png(buf)
          data = buf.getvalue()

          # pseudo-code for generating the http response from your
          # webserver, and writing the bytes back to the browser.
          # replace this with corresponding code for your web framework
          headers = {
          'Content-Type': 'image/png',
          'Content-Length': len(data)
          }
          response.write(200, 'OK', headers, data)


          Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.






          share|improve this answer

















          • 3




            It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
            – aaa90210
            Dec 14 '12 at 1:38


















          up vote
          1
          down vote













          Just to update for python3




          The StringIO and cStringIO modules are gone. Instead, import the io
          module and use io.StringIO
          https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio




          So now would be something like:



          import io
          from matplotlib.figure import Figure
          from matplotlib import pyplot as plt

          fig = Figure(figsize=[4,4])
          ax = fig.add_axes([.1,.1,.8,.8])
          ax.scatter([1,2], [3,4])

          buf = io.BytesIO()
          fig.savefig(buf, format='png')
          plt.close(fig)
          data=buf.getvalue()

          # In my case I would have used Django for the webpage
          response = HttpResponse(data, content_type='image/png')
          return response





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5515278%2fplot-matplotlib-on-the-web%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            20
            down vote



            accepted










            First you need a page to load a url from the webserver controller which generates the image:



            <img src="/matplot/makegraph?arg1=foo" />


            Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:



            import cStringIO
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_agg import FigureCanvasAgg

            fig = Figure(figsize=[4,4])
            ax = fig.add_axes([.1,.1,.8,.8])
            ax.scatter([1,2], [3,4])
            canvas = FigureCanvasAgg(fig)

            # write image data to a string buffer and get the PNG image bytes
            buf = cStringIO.StringIO()
            canvas.print_png(buf)
            data = buf.getvalue()

            # pseudo-code for generating the http response from your
            # webserver, and writing the bytes back to the browser.
            # replace this with corresponding code for your web framework
            headers = {
            'Content-Type': 'image/png',
            'Content-Length': len(data)
            }
            response.write(200, 'OK', headers, data)


            Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.






            share|improve this answer

















            • 3




              It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
              – aaa90210
              Dec 14 '12 at 1:38















            up vote
            20
            down vote



            accepted










            First you need a page to load a url from the webserver controller which generates the image:



            <img src="/matplot/makegraph?arg1=foo" />


            Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:



            import cStringIO
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_agg import FigureCanvasAgg

            fig = Figure(figsize=[4,4])
            ax = fig.add_axes([.1,.1,.8,.8])
            ax.scatter([1,2], [3,4])
            canvas = FigureCanvasAgg(fig)

            # write image data to a string buffer and get the PNG image bytes
            buf = cStringIO.StringIO()
            canvas.print_png(buf)
            data = buf.getvalue()

            # pseudo-code for generating the http response from your
            # webserver, and writing the bytes back to the browser.
            # replace this with corresponding code for your web framework
            headers = {
            'Content-Type': 'image/png',
            'Content-Length': len(data)
            }
            response.write(200, 'OK', headers, data)


            Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.






            share|improve this answer

















            • 3




              It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
              – aaa90210
              Dec 14 '12 at 1:38













            up vote
            20
            down vote



            accepted







            up vote
            20
            down vote



            accepted






            First you need a page to load a url from the webserver controller which generates the image:



            <img src="/matplot/makegraph?arg1=foo" />


            Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:



            import cStringIO
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_agg import FigureCanvasAgg

            fig = Figure(figsize=[4,4])
            ax = fig.add_axes([.1,.1,.8,.8])
            ax.scatter([1,2], [3,4])
            canvas = FigureCanvasAgg(fig)

            # write image data to a string buffer and get the PNG image bytes
            buf = cStringIO.StringIO()
            canvas.print_png(buf)
            data = buf.getvalue()

            # pseudo-code for generating the http response from your
            # webserver, and writing the bytes back to the browser.
            # replace this with corresponding code for your web framework
            headers = {
            'Content-Type': 'image/png',
            'Content-Length': len(data)
            }
            response.write(200, 'OK', headers, data)


            Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.






            share|improve this answer












            First you need a page to load a url from the webserver controller which generates the image:



            <img src="/matplot/makegraph?arg1=foo" />


            Then, embed the matplotlib code into the makegraph controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write the bytes back to the browser:



            import cStringIO
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_agg import FigureCanvasAgg

            fig = Figure(figsize=[4,4])
            ax = fig.add_axes([.1,.1,.8,.8])
            ax.scatter([1,2], [3,4])
            canvas = FigureCanvasAgg(fig)

            # write image data to a string buffer and get the PNG image bytes
            buf = cStringIO.StringIO()
            canvas.print_png(buf)
            data = buf.getvalue()

            # pseudo-code for generating the http response from your
            # webserver, and writing the bytes back to the browser.
            # replace this with corresponding code for your web framework
            headers = {
            'Content-Type': 'image/png',
            'Content-Length': len(data)
            }
            response.write(200, 'OK', headers, data)


            Note: you may want to add caching for these if they're frequently generated with the same arguments, e.g. construct a key from the args and write the image data to memcache, then check memcache before regenerating the graph.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 1 '11 at 16:09









            samplebias

            29.4k37992




            29.4k37992








            • 3




              It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
              – aaa90210
              Dec 14 '12 at 1:38














            • 3




              It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
              – aaa90210
              Dec 14 '12 at 1:38








            3




            3




            It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
            – aaa90210
            Dec 14 '12 at 1:38




            It appears you can also do plt.savefig(buf,format="png",facecolor="white") or fig.savefig(). So you dont have to deal with the canvas object.
            – aaa90210
            Dec 14 '12 at 1:38












            up vote
            1
            down vote













            Just to update for python3




            The StringIO and cStringIO modules are gone. Instead, import the io
            module and use io.StringIO
            https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio




            So now would be something like:



            import io
            from matplotlib.figure import Figure
            from matplotlib import pyplot as plt

            fig = Figure(figsize=[4,4])
            ax = fig.add_axes([.1,.1,.8,.8])
            ax.scatter([1,2], [3,4])

            buf = io.BytesIO()
            fig.savefig(buf, format='png')
            plt.close(fig)
            data=buf.getvalue()

            # In my case I would have used Django for the webpage
            response = HttpResponse(data, content_type='image/png')
            return response





            share|improve this answer

























              up vote
              1
              down vote













              Just to update for python3




              The StringIO and cStringIO modules are gone. Instead, import the io
              module and use io.StringIO
              https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio




              So now would be something like:



              import io
              from matplotlib.figure import Figure
              from matplotlib import pyplot as plt

              fig = Figure(figsize=[4,4])
              ax = fig.add_axes([.1,.1,.8,.8])
              ax.scatter([1,2], [3,4])

              buf = io.BytesIO()
              fig.savefig(buf, format='png')
              plt.close(fig)
              data=buf.getvalue()

              # In my case I would have used Django for the webpage
              response = HttpResponse(data, content_type='image/png')
              return response





              share|improve this answer























                up vote
                1
                down vote










                up vote
                1
                down vote









                Just to update for python3




                The StringIO and cStringIO modules are gone. Instead, import the io
                module and use io.StringIO
                https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio




                So now would be something like:



                import io
                from matplotlib.figure import Figure
                from matplotlib import pyplot as plt

                fig = Figure(figsize=[4,4])
                ax = fig.add_axes([.1,.1,.8,.8])
                ax.scatter([1,2], [3,4])

                buf = io.BytesIO()
                fig.savefig(buf, format='png')
                plt.close(fig)
                data=buf.getvalue()

                # In my case I would have used Django for the webpage
                response = HttpResponse(data, content_type='image/png')
                return response





                share|improve this answer












                Just to update for python3




                The StringIO and cStringIO modules are gone. Instead, import the io
                module and use io.StringIO
                https://docs.python.org/3.5/whatsnew/3.0.html?highlight=cstringio




                So now would be something like:



                import io
                from matplotlib.figure import Figure
                from matplotlib import pyplot as plt

                fig = Figure(figsize=[4,4])
                ax = fig.add_axes([.1,.1,.8,.8])
                ax.scatter([1,2], [3,4])

                buf = io.BytesIO()
                fig.savefig(buf, format='png')
                plt.close(fig)
                data=buf.getvalue()

                # In my case I would have used Django for the webpage
                response = HttpResponse(data, content_type='image/png')
                return response






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 8:43









                Dom

                111




                111






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5515278%2fplot-matplotlib-on-the-web%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine