How to show graphs from python program to a website?












1














I have a python file which plots graphs. I want to import that file to web-page which I want to make. Which tool will be better to make that web-page. It should be like, when i press some button the graph appears in a div or Iframe or another popup page.



The following code create a graph. I want to show the graph in website



import pandas as pd

import dateutil

def gen(file,data):

lists = pd.read_csv(file)

lists['obstime'] = lists['obstime'].apply(dateutil.parser.parse, dayfirst=True)

lists = lists[lists[data] > -273]

daily_avg_temp = lists.set_index('obstime').groupby(pd.Grouper(freq='D'))[data].mean()

monthly_avg_temp = daily_avg_temp.groupby(pd.Grouper(freq='M')).mean()
monthly_avg_temp.plot()

gen(file_name,d)









share|improve this question





























    1














    I have a python file which plots graphs. I want to import that file to web-page which I want to make. Which tool will be better to make that web-page. It should be like, when i press some button the graph appears in a div or Iframe or another popup page.



    The following code create a graph. I want to show the graph in website



    import pandas as pd

    import dateutil

    def gen(file,data):

    lists = pd.read_csv(file)

    lists['obstime'] = lists['obstime'].apply(dateutil.parser.parse, dayfirst=True)

    lists = lists[lists[data] > -273]

    daily_avg_temp = lists.set_index('obstime').groupby(pd.Grouper(freq='D'))[data].mean()

    monthly_avg_temp = daily_avg_temp.groupby(pd.Grouper(freq='M')).mean()
    monthly_avg_temp.plot()

    gen(file_name,d)









    share|improve this question



























      1












      1








      1







      I have a python file which plots graphs. I want to import that file to web-page which I want to make. Which tool will be better to make that web-page. It should be like, when i press some button the graph appears in a div or Iframe or another popup page.



      The following code create a graph. I want to show the graph in website



      import pandas as pd

      import dateutil

      def gen(file,data):

      lists = pd.read_csv(file)

      lists['obstime'] = lists['obstime'].apply(dateutil.parser.parse, dayfirst=True)

      lists = lists[lists[data] > -273]

      daily_avg_temp = lists.set_index('obstime').groupby(pd.Grouper(freq='D'))[data].mean()

      monthly_avg_temp = daily_avg_temp.groupby(pd.Grouper(freq='M')).mean()
      monthly_avg_temp.plot()

      gen(file_name,d)









      share|improve this question















      I have a python file which plots graphs. I want to import that file to web-page which I want to make. Which tool will be better to make that web-page. It should be like, when i press some button the graph appears in a div or Iframe or another popup page.



      The following code create a graph. I want to show the graph in website



      import pandas as pd

      import dateutil

      def gen(file,data):

      lists = pd.read_csv(file)

      lists['obstime'] = lists['obstime'].apply(dateutil.parser.parse, dayfirst=True)

      lists = lists[lists[data] > -273]

      daily_avg_temp = lists.set_index('obstime').groupby(pd.Grouper(freq='D'))[data].mean()

      monthly_avg_temp = daily_avg_temp.groupby(pd.Grouper(freq='M')).mean()
      monthly_avg_temp.plot()

      gen(file_name,d)






      php python-3.x web matplotlib flask






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 28 '18 at 9:27









      dferenc

      4,511122131




      4,511122131










      asked Dec 28 '18 at 9:06









      Dhiraj KumarDhiraj Kumar

      454




      454
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You can save the plot in a file-like BytesIO stream, then using send_file function from flask you can send it to the client to be rendered.



          from io import BytesIO

          import pandas as pd
          from flask import Flask, send_file

          @app.route('/plot')
          def plot():
          # your pandas code goes here ...

          plot = df.plot()
          stream = BytesIO()
          plot.figure.savefig(stream)
          stream.seek(0)
          return send_file(stream, mimetype='image/png')

          app.run(debug=True, port=8000)





          share|improve this answer





























            0














            I'm not sure if this is the best way to display a graph on a webpage, but I'd use a javascript charting library like Chart.js to plot your data. The chart would be responsive and dynamic: a simple button press with an AJAX request would change the plot.



            For example, you could plot monthly transactions like so (here I use Jinja 2 to get the data):



            HTML



            <div class="card border-primary">
            <div class="card-header">
            <h4 class="card-title text-primary">Monthly transactions</h4>
            </div>
            <div class="card-body">
            <canvas id="transactions-chart" width="600" height="400" aria-label="transactions-chart" role="img"></canvas>
            </div>
            </div>


            JAVASCRIPT



            <script>
            // Global parameters:
            Chart.defaults.global.responsive = true;

            // Define the chart data
            var chartDataMonth = {
            labels: [{% for item in days_labels %}"{{ item }}", {% endfor %}],
            datasets: [{
            label: 'Amount paid',
            fill: false,
            backgroundColor: "#dc3545",
            borderColor: "#dc3545",
            data: [{% for item in paid_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
            },
            {
            label: 'Amount topped up',
            fill: false,
            backgroundColor: "#007bff",
            borderColor: "#007bff",
            data: [{% for item in topped_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
            }]
            };

            // Get chart canvas
            var ctx = document.querySelector('#transactions-chart').getContext('2d');
            // Create the chart using the chart canvas
            var transactionsChart = new Chart(ctx, {
            type: 'line',
            data: chartDataMonth,
            options: {
            responsive: true,
            maintainAspectRatio: false,
            tooltips: {
            mode: 'index',
            intersect: false,
            callbacks: {
            label: function(tooltipItems, data) {
            return '€' + tooltipItems.yLabel;
            }
            }
            },
            hover: {
            mode: 'nearest',
            intersect: true
            },
            scales: {
            xAxes: [{
            display: true,
            scaleLabel: {
            display: true,
            labelString: 'Day'
            }
            }],
            yAxes: [{
            display: true,
            scaleLabel: {
            display: true,
            labelString: 'Amount'
            },
            ticks: {
            // Include a euro sign in the ticks
            callback: function(value, index, values) {
            return '€' + value;
            }
            }
            }]
            }
            }
            });
            </script>





            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',
              autoActivateHeartbeat: false,
              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%2f53956001%2fhow-to-show-graphs-from-python-program-to-a-website%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









              0














              You can save the plot in a file-like BytesIO stream, then using send_file function from flask you can send it to the client to be rendered.



              from io import BytesIO

              import pandas as pd
              from flask import Flask, send_file

              @app.route('/plot')
              def plot():
              # your pandas code goes here ...

              plot = df.plot()
              stream = BytesIO()
              plot.figure.savefig(stream)
              stream.seek(0)
              return send_file(stream, mimetype='image/png')

              app.run(debug=True, port=8000)





              share|improve this answer


























                0














                You can save the plot in a file-like BytesIO stream, then using send_file function from flask you can send it to the client to be rendered.



                from io import BytesIO

                import pandas as pd
                from flask import Flask, send_file

                @app.route('/plot')
                def plot():
                # your pandas code goes here ...

                plot = df.plot()
                stream = BytesIO()
                plot.figure.savefig(stream)
                stream.seek(0)
                return send_file(stream, mimetype='image/png')

                app.run(debug=True, port=8000)





                share|improve this answer
























                  0












                  0








                  0






                  You can save the plot in a file-like BytesIO stream, then using send_file function from flask you can send it to the client to be rendered.



                  from io import BytesIO

                  import pandas as pd
                  from flask import Flask, send_file

                  @app.route('/plot')
                  def plot():
                  # your pandas code goes here ...

                  plot = df.plot()
                  stream = BytesIO()
                  plot.figure.savefig(stream)
                  stream.seek(0)
                  return send_file(stream, mimetype='image/png')

                  app.run(debug=True, port=8000)





                  share|improve this answer












                  You can save the plot in a file-like BytesIO stream, then using send_file function from flask you can send it to the client to be rendered.



                  from io import BytesIO

                  import pandas as pd
                  from flask import Flask, send_file

                  @app.route('/plot')
                  def plot():
                  # your pandas code goes here ...

                  plot = df.plot()
                  stream = BytesIO()
                  plot.figure.savefig(stream)
                  stream.seek(0)
                  return send_file(stream, mimetype='image/png')

                  app.run(debug=True, port=8000)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 28 '18 at 10:07









                  OMar MohamedOMar Mohamed

                  12029




                  12029

























                      0














                      I'm not sure if this is the best way to display a graph on a webpage, but I'd use a javascript charting library like Chart.js to plot your data. The chart would be responsive and dynamic: a simple button press with an AJAX request would change the plot.



                      For example, you could plot monthly transactions like so (here I use Jinja 2 to get the data):



                      HTML



                      <div class="card border-primary">
                      <div class="card-header">
                      <h4 class="card-title text-primary">Monthly transactions</h4>
                      </div>
                      <div class="card-body">
                      <canvas id="transactions-chart" width="600" height="400" aria-label="transactions-chart" role="img"></canvas>
                      </div>
                      </div>


                      JAVASCRIPT



                      <script>
                      // Global parameters:
                      Chart.defaults.global.responsive = true;

                      // Define the chart data
                      var chartDataMonth = {
                      labels: [{% for item in days_labels %}"{{ item }}", {% endfor %}],
                      datasets: [{
                      label: 'Amount paid',
                      fill: false,
                      backgroundColor: "#dc3545",
                      borderColor: "#dc3545",
                      data: [{% for item in paid_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                      },
                      {
                      label: 'Amount topped up',
                      fill: false,
                      backgroundColor: "#007bff",
                      borderColor: "#007bff",
                      data: [{% for item in topped_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                      }]
                      };

                      // Get chart canvas
                      var ctx = document.querySelector('#transactions-chart').getContext('2d');
                      // Create the chart using the chart canvas
                      var transactionsChart = new Chart(ctx, {
                      type: 'line',
                      data: chartDataMonth,
                      options: {
                      responsive: true,
                      maintainAspectRatio: false,
                      tooltips: {
                      mode: 'index',
                      intersect: false,
                      callbacks: {
                      label: function(tooltipItems, data) {
                      return '€' + tooltipItems.yLabel;
                      }
                      }
                      },
                      hover: {
                      mode: 'nearest',
                      intersect: true
                      },
                      scales: {
                      xAxes: [{
                      display: true,
                      scaleLabel: {
                      display: true,
                      labelString: 'Day'
                      }
                      }],
                      yAxes: [{
                      display: true,
                      scaleLabel: {
                      display: true,
                      labelString: 'Amount'
                      },
                      ticks: {
                      // Include a euro sign in the ticks
                      callback: function(value, index, values) {
                      return '€' + value;
                      }
                      }
                      }]
                      }
                      }
                      });
                      </script>





                      share|improve this answer


























                        0














                        I'm not sure if this is the best way to display a graph on a webpage, but I'd use a javascript charting library like Chart.js to plot your data. The chart would be responsive and dynamic: a simple button press with an AJAX request would change the plot.



                        For example, you could plot monthly transactions like so (here I use Jinja 2 to get the data):



                        HTML



                        <div class="card border-primary">
                        <div class="card-header">
                        <h4 class="card-title text-primary">Monthly transactions</h4>
                        </div>
                        <div class="card-body">
                        <canvas id="transactions-chart" width="600" height="400" aria-label="transactions-chart" role="img"></canvas>
                        </div>
                        </div>


                        JAVASCRIPT



                        <script>
                        // Global parameters:
                        Chart.defaults.global.responsive = true;

                        // Define the chart data
                        var chartDataMonth = {
                        labels: [{% for item in days_labels %}"{{ item }}", {% endfor %}],
                        datasets: [{
                        label: 'Amount paid',
                        fill: false,
                        backgroundColor: "#dc3545",
                        borderColor: "#dc3545",
                        data: [{% for item in paid_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                        },
                        {
                        label: 'Amount topped up',
                        fill: false,
                        backgroundColor: "#007bff",
                        borderColor: "#007bff",
                        data: [{% for item in topped_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                        }]
                        };

                        // Get chart canvas
                        var ctx = document.querySelector('#transactions-chart').getContext('2d');
                        // Create the chart using the chart canvas
                        var transactionsChart = new Chart(ctx, {
                        type: 'line',
                        data: chartDataMonth,
                        options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        tooltips: {
                        mode: 'index',
                        intersect: false,
                        callbacks: {
                        label: function(tooltipItems, data) {
                        return '€' + tooltipItems.yLabel;
                        }
                        }
                        },
                        hover: {
                        mode: 'nearest',
                        intersect: true
                        },
                        scales: {
                        xAxes: [{
                        display: true,
                        scaleLabel: {
                        display: true,
                        labelString: 'Day'
                        }
                        }],
                        yAxes: [{
                        display: true,
                        scaleLabel: {
                        display: true,
                        labelString: 'Amount'
                        },
                        ticks: {
                        // Include a euro sign in the ticks
                        callback: function(value, index, values) {
                        return '€' + value;
                        }
                        }
                        }]
                        }
                        }
                        });
                        </script>





                        share|improve this answer
























                          0












                          0








                          0






                          I'm not sure if this is the best way to display a graph on a webpage, but I'd use a javascript charting library like Chart.js to plot your data. The chart would be responsive and dynamic: a simple button press with an AJAX request would change the plot.



                          For example, you could plot monthly transactions like so (here I use Jinja 2 to get the data):



                          HTML



                          <div class="card border-primary">
                          <div class="card-header">
                          <h4 class="card-title text-primary">Monthly transactions</h4>
                          </div>
                          <div class="card-body">
                          <canvas id="transactions-chart" width="600" height="400" aria-label="transactions-chart" role="img"></canvas>
                          </div>
                          </div>


                          JAVASCRIPT



                          <script>
                          // Global parameters:
                          Chart.defaults.global.responsive = true;

                          // Define the chart data
                          var chartDataMonth = {
                          labels: [{% for item in days_labels %}"{{ item }}", {% endfor %}],
                          datasets: [{
                          label: 'Amount paid',
                          fill: false,
                          backgroundColor: "#dc3545",
                          borderColor: "#dc3545",
                          data: [{% for item in paid_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                          },
                          {
                          label: 'Amount topped up',
                          fill: false,
                          backgroundColor: "#007bff",
                          borderColor: "#007bff",
                          data: [{% for item in topped_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                          }]
                          };

                          // Get chart canvas
                          var ctx = document.querySelector('#transactions-chart').getContext('2d');
                          // Create the chart using the chart canvas
                          var transactionsChart = new Chart(ctx, {
                          type: 'line',
                          data: chartDataMonth,
                          options: {
                          responsive: true,
                          maintainAspectRatio: false,
                          tooltips: {
                          mode: 'index',
                          intersect: false,
                          callbacks: {
                          label: function(tooltipItems, data) {
                          return '€' + tooltipItems.yLabel;
                          }
                          }
                          },
                          hover: {
                          mode: 'nearest',
                          intersect: true
                          },
                          scales: {
                          xAxes: [{
                          display: true,
                          scaleLabel: {
                          display: true,
                          labelString: 'Day'
                          }
                          }],
                          yAxes: [{
                          display: true,
                          scaleLabel: {
                          display: true,
                          labelString: 'Amount'
                          },
                          ticks: {
                          // Include a euro sign in the ticks
                          callback: function(value, index, values) {
                          return '€' + value;
                          }
                          }
                          }]
                          }
                          }
                          });
                          </script>





                          share|improve this answer












                          I'm not sure if this is the best way to display a graph on a webpage, but I'd use a javascript charting library like Chart.js to plot your data. The chart would be responsive and dynamic: a simple button press with an AJAX request would change the plot.



                          For example, you could plot monthly transactions like so (here I use Jinja 2 to get the data):



                          HTML



                          <div class="card border-primary">
                          <div class="card-header">
                          <h4 class="card-title text-primary">Monthly transactions</h4>
                          </div>
                          <div class="card-body">
                          <canvas id="transactions-chart" width="600" height="400" aria-label="transactions-chart" role="img"></canvas>
                          </div>
                          </div>


                          JAVASCRIPT



                          <script>
                          // Global parameters:
                          Chart.defaults.global.responsive = true;

                          // Define the chart data
                          var chartDataMonth = {
                          labels: [{% for item in days_labels %}"{{ item }}", {% endfor %}],
                          datasets: [{
                          label: 'Amount paid',
                          fill: false,
                          backgroundColor: "#dc3545",
                          borderColor: "#dc3545",
                          data: [{% for item in paid_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                          },
                          {
                          label: 'Amount topped up',
                          fill: false,
                          backgroundColor: "#007bff",
                          borderColor: "#007bff",
                          data: [{% for item in topped_this_month %}{{ '%0.2f'| format(item|float) }}, {% endfor %}],
                          }]
                          };

                          // Get chart canvas
                          var ctx = document.querySelector('#transactions-chart').getContext('2d');
                          // Create the chart using the chart canvas
                          var transactionsChart = new Chart(ctx, {
                          type: 'line',
                          data: chartDataMonth,
                          options: {
                          responsive: true,
                          maintainAspectRatio: false,
                          tooltips: {
                          mode: 'index',
                          intersect: false,
                          callbacks: {
                          label: function(tooltipItems, data) {
                          return '€' + tooltipItems.yLabel;
                          }
                          }
                          },
                          hover: {
                          mode: 'nearest',
                          intersect: true
                          },
                          scales: {
                          xAxes: [{
                          display: true,
                          scaleLabel: {
                          display: true,
                          labelString: 'Day'
                          }
                          }],
                          yAxes: [{
                          display: true,
                          scaleLabel: {
                          display: true,
                          labelString: 'Amount'
                          },
                          ticks: {
                          // Include a euro sign in the ticks
                          callback: function(value, index, values) {
                          return '€' + value;
                          }
                          }
                          }]
                          }
                          }
                          });
                          </script>






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 28 '18 at 9:58









                          Samuel DieboltSamuel Diebolt

                          66




                          66






























                              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%2f53956001%2fhow-to-show-graphs-from-python-program-to-a-website%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

                              Monofisismo

                              Angular Downloading a file using contenturl with Basic Authentication

                              Olmecas