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

AI and the Insurance Industry

  Hari Nair Needing insurance is like needing a parachute. If it isn't there the first time, chances are you won't be needing it again. --Author unknown Building customer relationships and managing risks are key for Insurance companies. Insurance companies are making extensive use of AI  are reaping the benefits of increased customer satisfaction adding to their bottom line.  AI has the potential to transform the insurance experience for customers from frustrating and bureaucratic to something fast, on-demand, and more affordable. Tailor-made insurance products will attract more customers at fairer prices. If insurers apply AI tech to the mountain of data at their disposal, we will soon start to see more flexible insurance such as on-demand pay-as-you-go insurance, and premiums that automatically adjust in response to accidents, customer health, etc.   Insurers have yet to unlock the full potential of AI. Machine learning use cases in Insu...

A quick introduction to AI and ML

Hari Nair Artificial intelligence (AI) is a branch of computer science. Its main goal is to create smart machines that can learn on their own and are capable of thinking like humans. The term 'artificial intelligence' commonly applies to devices or applications capable of carrying out specific tasks in human ways, by mimicking cognitive functions such as: • learning • reasoning • problem-solving • visual perception • language-understanding There are two main types of AI: Applied AI - is more common and includes systems designed to intelligently carry out a single task, example: move a driverless vehicle. This category is also known as 'weak' or 'narrow' AI. Generalized AI - is less common and includes systems or devices that can theoretically handle any task, as they carry enough intelligence to find solutions to unfamiliar problems. Generalized AI is also known as 'strong' AI. Examples of true strong AI don't curren...

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 ...