Analysing the Data through visualization is the best way to understand them. It feels bored when you just look at the inferred numbers and not gain much information. It requires much time to spend for filtering out the outcomes and reasons. Therefore rather than extracting analysis from the numbers you should visualize the data using the different figures. In this post, you will learn how to create a bar chart from data frame using Plotly and how to integrate it with you Flask Web APP.
Step by Step for creating a Bar Chart?
Step 1: Import the necessary libraries
The first step is to import the necessary libraries. I am using Plotly for plot in the chart and Flask for integrating flask with Plotly. Pandas for reading the CSV and manipulation of the excel.
from flask import Flask,render_template import pandas as pd import numpy as np from charts.bar_chart import plot_chart import plotly.graph_objs as go import plotly.offline as plt
Step 2: Load the Dataset.
You will plot the chart for a real-life example. Therefore I have a dataset for the countries population, GDP e.t.c. You can download from here.
df = pd.read_csv("countries.csv")
Step 3: Configure the Layout and the Data for the Plot.
Plotly requires the data and layout for plotting. First, you will create a trace for the bar chart and then pass the x-axis and y-axis values you want to plot. In this case, I want x-axis as country name and y-axis GDP data. Use the following code
trace = go.Bar(x=df["Country"][0:20], y=df["GDP ($ per capita)"]) layout = go.Layout(title="GDP of the Country", xaxis=dict(title="Country"), yaxis=dict(title="GDP Per Capita"), ) data = [trace1] fig = go.Figure(data=data, layout=layout) plt.plot(fig)
Step 4: Integrate it with the Flask App.
The above method is only for plotting the Chart offline. If you want to integrate this chart with the Flask App. then you have to dump the figure into JSON Object. As figures generated by the Ploty framework is in dictionary and list format. Here I am passing the JSON to the flask app with the variable name plot. Let’s create the Flask Route and add the above code inside it. Use the following code
@app.route("/bar_chart") def bar_chart_plot(): df = pd.read_csv("countries.csv") trace1 = go.Bar(x=df["Country"][0:20], y=df["GDP ($ per capita)"]) layout = go.Layout(title="GDP of the Country", xaxis=dict(title="Country"), yaxis=dict(title="GDP Per Capita"), ) data = [trace1] fig = go.Figure(data=data, layout=layout) fig_json = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return render_template('charts.html', plot=fig_json)
When you run the Flask App you will get the output like this.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.