Skip to main content

Charts using Python



"A picture is worth a thousand words - Python and Charts"

Data visualization is the graphical representation of  data. Python provides an easy way (charts, graphs, and maps) to see and understand trends, outliers, and patterns in data.

  • Transform data into visualizations
  • Extract information and better understand the data
  • Customize and organize visualizations
  • Add interactivity to charts
Matplotlib is a plotting library which produces charts in a variety of formats and interactive environments across platforms.

Installing packages


The following examples uses 2 basic charting libraries
How to install plotlib and seaborn charting libraries

pip install plotlib
pip install seaborn

Example-1
A simple chart using Randon numbers

c1.py
import matplotlib.pyplot as plt
import numpy as np
x = np.random.random((10, 1))
print(x)
plt.plot(x, '*-')
plt.show()

Output



Example-2

# Example-2.py

import matplotlib.pyplot as plt

# Sales in M U.S $
height = [3, 12, 5, 18, 45]
bars = ('Jan', 'Feb', 'March', 'April', 'May')

# Choose the position of each barplots on the x-axis
y_pos = [0,1,2,3,4]

# Create bars
plt.bar(y_pos, height)

# Create names on the x-axis
plt.xticks(y_pos, bars)

# Show graphic
plt.show()

Output



There are many charts and formats available and is one of the best and easy to use charting library available today.

Word clouds are a great way to visualize sentiment, get a handle on a big chunk of text, and turn an otherwise drab article into a work of art. A Wordcloud is a visual representation of text Data. It displays a list of Words, the importance of each being shown with Font size or Color.

Let us look into the picture and its python code




#Examplie-3.py

from wordcloud import WordCloud
import matplotlib.pyplot as plt
# Create a list of word

text=("Emergys SAP  SAP-BusinessOne  S/4-HANA https://emergys.com/ Rpaide Emergys Software Private Limited Enterprise Resource Planning Emergys LLC Manufacturing Execution System Customer Relationship Manager Product Life Cycle Management S4H HCM SCM Business Intelligence Analytics")

# Create the wordcloud object
wordcloud = WordCloud(width=480, height=480, margin=0).generate(text)

# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.margins(x=0, y=0)
plt.show()



#Examplie-4.py
# python charts

from matplotlib import pyplot as plt
import numpy as np

# create data
x = np.random.rand(15)
y = x+np.random.rand(15)
z = x+np.random.rand(15)
z=z*z

# Use it with a call in cmap
#plt.scatter(x, y, s=z*2000, c=x, cmap="BuPu", alpha=0.4, edgecolors="grey", linewidth=2)

# You can reverse it:
#plt.scatter(x, y, s=z*2000, c=x, cmap="BuPu_r", alpha=0.4, edgecolors="grey", linewidth=2)

# OTHER: viridis / inferno / plasma / magma
plt.scatter(x, y, s=z*2000, c=x, cmap="plasma", alpha=0.4, edgecolors="grey", linewidth=2)
plt.show()

Output




Examplie-4.py

# 3D chart
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


def cc(arg):
 
    return mcolors.to_rgba(arg, alpha=0.6)


def polygon_under_graph(xlist, ylist):
 
    return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)]


fig = plt.figure()
ax = fig.gca(projection='3d')

verts = []

xs = np.linspace(0., 10., 26)

zs = range(4)

for i in zs:
    ys = np.random.rand(len(xs))
    verts.append(polygon_under_graph(xs, ys))

poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')])
ax.add_collection3d(poly, zs=zs, zdir='y')

ax.set_xlabel('Temp')
ax.set_ylabel('Pressure')
ax.set_zlabel('Time')
ax.set_xlim(0, 10)
ax.set_ylim(-1, 4)
ax.set_zlim(0, 1)

plt.show()


Output



M S SQL and python

#
# dash1.py
#
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
import pandas as pd

#import sqlite3
#conn = sqlite3.connect("DESKTOP-7KAT3LB\SQLEXPRESS")

import pyodbc
conn = pyodbc.connect('Driver={mssqlodbc};'
                      'DESKTOP-7KAT3LB\SQLEXPRESS;'
                      'Database=RB;'
                      'Trusted_Connection=yes;')

import plotly.graph_objs as go
c = conn.cursor()
df = pd.read_sql("SELECT  *  FROM npa1 where qtr='Qtr-1'", conn)
df = df[['Year_month', 'Loan_Category', 'Approved_amountt', 'Collected_amount']]
df.head(1)

Ploty and Dash

Plotly is a free and open-source graphing library for Python
Built on top of the Plotly JavaScript library (plotly.js), plotly.py enables Python users to create beautiful interactive web-based visualizations that can be displayed in Jupyter notebooks, saved to standalone HTML files, or served as part of pure Python-built web applications using Dash.

#plot0.py

import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.write_html('first_figure.html', auto_open=True)


#plot1.py

import plotly.express as px

df = px.data.gapminder()

fig = px.bar(df,
             x='continent',
             y='gdpPercap',
             color='continent',
             animation_frame='year',
             animation_group='country',
             range_y=[0, 1000000])
fig.show()





#plot2.py

import plotly.express as px
df = px.data.gapminder()
fig=px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country",
           log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])
fig.show()



Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.



Visit https://python-graph-gallery.com/all-charts/


Hari Nair

Popular posts from this blog

Machine Learning in Healthcare

Hari Nair Hospitals are constantly trying to improve the quality of care they deliver.  Machine learning (ML)  is creating disruptive changes in the healthcare industry.  ML was first applied to tailoring antibiotic dosages for patients in the 1970s..  Python developers can build solutions that benefit human health and well-being. Python and its frameworks work on principles  agreed upon the HIPAA checklist. Some of the practical areas for ML are: Medical image processing and anomaly detection Managing Hospitals and Patient Care Diagnostics Disease Prognosis Prediction Natural Language Processing (NLP) for Administrative Tasks Patient Risk Identification Computer vision methods have long been employed to automatically analyze biomedical images. The recent advent of deep learning has replaced many other machine learning methods, since it avoids the creation of hand-engineering features;  removing a critical source of error from the pro...

Computer vision

Computer vision   has received a lot of attention recently due to the popularity of Deep learning. Traditional machine learning algorithms are still very simple. Their training requires a lot of domain expertise and human intervention when errors occur.   OpenCV is one of the most popular library for computer vision. Every Machine Learning algorithm takes a Dataset as input and learns from this data. The algorithm goes through the data and identifies patterns in the data.  Deep learning algorithms, on the other hand, learn about the task at hand through a network of neurons that map the task as a hierarchy of concepts . Gray-scale image buffer which stores  image . Each pixel’s brightness is represented by a single 8-bit number, whose range is from 0 (black) to 255 (white) Deep learning algorithms also perform better when more data is given, which is not typical of machine learning algorithms.   The best applications of Googl...

Digital transformation in BFSI

Hari Nair It is not enough to just import technologies like AI, Block-chain or smartphones into existing financial services, says futurist and Fin-tech entrepreneur  --Brett King. The two biggest issues facing the majority of Bank customers today are service delays and poor quality of personalization. Now that we have chat-bots that have become more and more intelligent every year with conversational interface design, personal banking is significantly improved. AI is bringing upon a digital revolution to banking.  Fin-tech is an industry aiming to disrupt financial services using Artificial Intelligence.  By reducing waiting time, the bank can get-rid-of  long ques and help customers get personalized services quicker. AI has the potential to eliminate human error in banking procedures, allowing banks to better understand customer demands, make credit cards extinct, and influence the attraction of the unbanked to financial services. Fintech is ...