How to Create a Bar Chart From a DataFrame in Python
How to Create a Bar Chart From a DataFrame in Python

How to Create a Bar Chart From a DataFrame in Python ? (Plotly + Flask)

GET FREE AMZAON AUDIOBOOKS

Analyzing 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 plotting 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 it from here.

Kaggle Countries of the World Dataset

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 the x-axis as country name and the y-axis as 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 are 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)

In the last line of the function, you will pass the HTML file name and plot variable for using it in an HTML file. Below is the code that will contain inside the HTML File. Create a “charts.html” file and put the following things. Plotly requires d3 js and plotly.js for showing charts to the HTML. Therefore I have added both scripts inside the head section. In the body part, I am calling the Ploty.plot() javascript method for creating the bar chart for the data and layout we get as the JSON format.

<head>

<script src=”https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js”></script>

<script src=”https://cdn.plot.ly/plotly-latest.min.js”></script>

</head>

<body>

<div class=”chart” id=”barchart”>
<script>
        var fig = {{plot | safe}};
        Plotly.plot(‘barchart’,fig.data,fig.layout,{displaylogo: false});
    </script>
</div>

</body>

When you run the Flask App you will get the output like this.

Create a bart chart : Plotly

 

Other Methods

There is also another method to create a bar chart from dataframe in python. You can use directly pandas python packages for that. To do this you will use the pandas.DataFrame.plot.bar() function. It accepts the x and y-axis values you want to draw the bar. Below is the demo code for creating a simple bar chart from dataframe using the pandas module.

import pandas as pd
df = pd.DataFrame({'x':['A', 'B', 'C'], 'y':[100, 200, 300]})
ax = df.plot.bar(x='x', y='y')

Output

Creating dataframe bar chart using pandas
Creating dataframe bar chart using pandas

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner