"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.
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()
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()
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)
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
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
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()
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()
Visit https://python-graph-gallery.com/all-charts/
Hari Nair