0% found this document useful (0 votes)
12 views

UNIT3 (1)

Unit III covers data visualization techniques using Matplotlib, including simple line and scatter plots, bar charts, histograms, and pie charts. It explains how to customize plots with legends, colors, and annotations, as well as how to install and import Matplotlib. The document provides code examples for creating various types of plots and emphasizes the importance of data visualization in decision-making and data analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

UNIT3 (1)

Unit III covers data visualization techniques using Matplotlib, including simple line and scatter plots, bar charts, histograms, and pie charts. It explains how to customize plots with legends, colors, and annotations, as well as how to install and import Matplotlib. The document provides code examples for creating various types of plots and emphasizes the importance of data visualization in decision-making and data analysis.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

UNIT III

Visualization with Matplotlib


Simple Line Plots,Simple Scatter Plots,Visualizing Errors,Density and
Contour Plots,Histograms, Binnings, and Density.Customizing Plot
Legends,Customizing Colorbars,Multiple Subplots,Text and
Annotation,Customizing Ticks,Customizing Matplotlib: Configurations
and Stylesheets,Three-Dimensional Plotting in Matplotlib
Visualization
• Data Visualization is the process of presenting data in the form of
graphs or charts.
• It helps to understand large and complex amounts of data very
easily.
• It allows the decision-makers to make decisions very efficiently and
also allows them in identifying new trends and patterns very easily.
• It is also used in high-level data analysis for Machine Learning and
Exploratory Data Analysis (EDA).
• Data visualization can be done with various tools like Tableau, Power
BI, Python.
Matplotlib
• Matploptib is a low-level library of Python which is used for data
visualization.
• It is easy to use and emulates MATLAB like graphs and visualization.
• This library is built on the top of NumPy arrays and consist of several
plots like line chart, bar chart, histogram, etc.
• It provides a lot of flexibility but at the cost of writing more code.
Installation and Importing matplotlib

Command used to install matplotlib


pip install matplotlib
from matplotlib import pyplot as plt
or
import matplotlib.pyplot as plt
matplotlib.pyplot
• Pyplot is a Matplotlib module which provides a MATLAB-like
interface.
• Matplotlib is designed to be as usable as MATLAB, with the ability to
use Python and the advantage of being free and open-source.
• Each pyplot function makes some change to a figure: e.g., creates a
figure, creates a plotting area in a figure, plots some lines in a plotting
area, decorates the plot with labels, etc
• he various plots we can utilize using Pyplot are Line
Plot, Histogram, Scatter, 3D Plot, Image, Contour, and Polar.
Drawing Simple Line

import matplotlib.pyplot as plt


plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20])
plt.show()
Drawing Simple Line
• Parameters: This function accepts parameters that enables us to set axes
scales and format the graphs. These parameters are mentioned below :-
• plot(x, y): plot x and y using default line style and color.
• plot.axis([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from
minimum to maximum values
• plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2,
markersize=12): x and y co-ordinates are marked using circular markers of
size 12 and green color line with — style of width 2
• plot.xlabel(‘X-axis’): names x-axis
• plot.ylabel(‘Y-axis’): names y-axis
• plot(x, y, label = ‘Sample line ‘) plotted Sample Line will be displayed as a
legend
Drawing Simple Line
import matplotlib.pyplot as pt
pt.plot([1,2,3,4],[10,20,30,40],color
='orange',linestyle='dashed',linewidth=5)
pt.axis([0,10,0,50])
pt.xlabel("X-axis")
pt.ylabel("Y-axis")
pt.title("Sample Line")
pt.show()
Simple Scatter Plots
• A scatter plot is a diagram where each value in the data set is
represented by a dot.
• Scatter plots are used to observe relationship between variables and
uses dots to represent the relationship between them
• The scatter() method in the matplotlib library is used to draw a
scatter plot.
• Scatter plots are widely used to represent relation among variables
and how change in one affects the other.
Simple Scatter Plots
Syntax
• The syntax for scatter() method is given below:
matplotlib.pyplot.scatter(x_axis_data, y_axis_data, s=None, c=None, marker=None, cmap=None,
vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)
• The scatter() method takes in the following parameters:

• x_axis_data- An array containing x-axis data


• y_axis_data- An array containing y-axis data
• s- marker size (can be scalar or array of size equal to size of x or y)
• c- color of sequence of colors for markers
• marker- marker style
• cmap- cmap name
• linewidths- width of marker border
• edgecolor- marker border color
• alpha- blending value, between 0 (transparent) and 1 (opaque)
Example on Scatter Plot
import matplotlib.pyplot as plt
x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y =[99, 86, 87, 88, 100, 86,103, 87, 94, 78, 77, 85, 86]
plt.scatter(x, y, c ="blue")
# To show the plot
plt.show()
Example on Scatter Plot
import matplotlib.pyplot as plt
# dataset-1
x1 = [89, 43, 36, 36, 95, 10,66, 34, 38, 20]
y1 = [21, 46, 3, 35, 67, 95,53, 72, 58, 10]
# dataset2
x2 = [26, 29, 48, 64, 6, 5,36, 66, 72, 40]
y2 = [26, 34, 90, 33, 38,20, 56, 2, 47, 15]
plt.scatter(x1, y1, c ="pink",linewidths = 2,marker ="s",edgecolor ="green",s = 50)
plt.scatter(x2, y2, c ="yellow",linewidths = 2,marker ="^",edgecolor ="red",s = 200)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Bar Plot
• A bar plot or bar chart is a graph that represents the category of data
with rectangular bars with lengths and heights that is proportional to
the values which they represent.
• The bar plots can be plotted horizontally or vertically.
• A bar chart describes the comparisons between the discrete
categories.
• One of the axis of the plot represents the specific categories being
compared, while the other axis represents the measured values
corresponding to those categories.
Creating a bar plot
• The matplotlib API in Python provides the bar() function which can
be used in MATLAB style use or as an object-oriented API.
• The syntax of the bar() function to be used with the axes is as
follows:-
plt.bar(x,height,width,bottom,align)
x: A sequence of scalars that are the x-coordinates of the bars.
height: A sequence of scalars that are the height(s) of the bars.
width(Optional): An array containing the width of the bars.
bottom(Optional): An array containing the y coordinate(s) of the bases
of the bars
allign(Optional):Has two possible values centre or edge
Simple Example on Barplot
import matplotlib.pyplot as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30,'Python':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
plt.bar(courses, values, color ='maroon', width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()
Vertical Bar Chart
import matplotlib.pyplot as plt

# Pass the x and y cordinates of the bars to the


# function. The label argument gives a label to the data.
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Data 1")
plt.legend()

# The following commands add labels to our figure.


plt.xlabel('X values')
plt.ylabel('Height')
plt.title('Vertical Bar chart')

plt.show()
Horizontal Bar Chart
import matplotlib.pyplot as plt

# Pass the x and y cordinates of the bars to the


# function. The label argument gives a label to the data.
plt.barh(["Cats","Dogs","Goldfish","Snakes","Turtles"],
[5,2,7,8,2], align='center', label="Data 1")
plt.legend()

plt.ylabel('Pets')
plt.xlabel('Popularity')
plt.title('Popularity of pets in the neighbourhood')

plt.show()
Comparing two data series
import numpy as np
import matplotlib.pyplot as plt
# data to plot
marks_john = [90, 55, 40, 65]
marks_sam = [85, 62, 54, 20]
# create plot
fig, ax = plt.subplots()
bar_width = 0.35
X = np.arange(4)
p1 = plt.bar(X, marks_john, bar_width, color='b',label='John')
# The bar of second plot starts where the first bar ends
p2 = plt.bar(X + bar_width, marks_sam, bar_width,color='g',label='Sam')
plt.xlabel('Subject')
plt.ylabel('Scores')
plt.title('Scores in each subject')
plt.xticks(X + (bar_width/2) , ("English", "Science","Sports", "History"))
plt.legend()
plt.tight_layout()
plt.show()
Histogram

• A histogram is basically used to represent data provided in a form of


some groups.
• It is accurate method for the graphical representation of numerical
data distribution.
• It is a type of bar plot where X-axis represents the bin ranges while Y-
axis gives information about frequency.
Histogram
from matplotlib import pyplot as plt
# Creating dataset
a = [22, 87, 5, 43, 56,73, 55, 54, 11,20, 51, 5, 79, 31,27]
# Creating histogram
fig = plt.figure(figsize = (10, 5))
plt.hist(a, bins = [0, 25, 50, 75, 100],edgecolor='black')
# Show plot
plt.show()
Histogram
import pandas as pd
import openpyxl
import matplotlib.pyplot as ppt
#Reading Dataset
data = pd.read_excel('E:\Data Science with Python\FirstIA.xlsx')
print(data)
#Get column which is required
usecol=list(data['Data Science'])
print(usecol)
#Drawing Histogram
ppt.hist(usecol,bins=6)
ppt.show()
Histogram
import matplotlib.pyplot as plt
x = [1, 1, 2, 3, 3, 5, 7, 8, 9, 10,
10, 11, 11, 13, 13, 15, 16, 17, 18, 18,
18, 19, 20, 21, 21, 23, 24, 24, 25, 25,
25, 25, 26, 26, 26, 27, 27, 27, 27, 27,
29, 30, 30, 31, 33, 34, 34, 34, 35, 36,
36, 37, 37, 38, 38, 39, 40, 41, 41, 42,
43, 44, 45, 45, 46, 47, 48, 48, 49, 50,
51, 52, 53, 54, 55, 55, 56, 57, 58, 60,
61, 63, 64, 65, 66, 68, 70, 71, 72, 74,
75, 77, 81, 83, 84, 87, 89, 90, 90, 91
]
plt.hist(x, bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 99])
plt.show()
Pie Chart
• A Pie Chart is a circular statistical plot that can display only one series of
data.
• The area of the chart is the total percentage of the given data.
• The area of slices of the pie represents the percentage of the parts of the
data.
• The slices of pie are called wedges.
• The area of the wedge is determined by the length of the arc of the wedge.
• The area of a wedge represents the relative percentage of that part with
respect to whole data.
• Pie charts are commonly used in business presentations like sales,
operations, survey results, resources, etc as they provide a quick summary.
Creating Pie Chart
• Syntax:
• matplotlib.pyplot.pie(data, labels=None, colors=None, autopct=None,
shadow=False)
Parameters:
data represents the array of data values to be plotted, the fractional area
of each slice is represented by data/sum(data). If sum(data)<1, then the
data values returns the fractional area directly, thus resulting pie will have
empty wedge of size 1-sum(data).
labels is a list of sequence of strings which sets the label of each wedge.
color attribute is used to provide color to the wedges.
autopct is a string used to label the wedge with their numerical value.
shadow is used to create shadow of wedge.
Creating Pie Chart
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
# show plot
plt.show()
Show Percentages on Slices
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%')
plt.show()
Explode/Highlight Wedges
from matplotlib import pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
explode = [0.1, 0, 0, 0, 0.2]
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
ax.pie(students, labels = langs,autopct='%1.2f%%',explode=explode)
plt.show()
Adding a Shadow
import matplotlib.pyplot as plt
x = [15, 25, 25, 30, 5]
labels = ['Very Likely', 'Likely', 'Unsure', 'Unlikely', 'Very Unlikely']
colors = ['tab:blue', 'tab:cyan', 'tab:gray', 'tab:orange', 'tab:red']
explode = [0, 0, 0, 0, 0.2]
fig, ax = plt.subplots()
ax.pie(x, labels = labels,
colors = colors,
autopct='%.0f%%',
explode = explode,
shadow = True)

ax.set_title('Survery responses')
plt.show()
Rotating Pie Chart
import matplotlib.pyplot as plt
x = [15, 25, 25, 30, 5]
labels = ['Very Likely', 'Likely', 'Unsure', 'Unlikely', 'Very Unlikely']
colors = ['tab:blue', 'tab:cyan', 'tab:gray', 'tab:orange', 'tab:red']
explode = [0, 0, 0, 0, 0.2]
fig, ax = plt.subplots()
ax.pie(x, labels = labels,
colors = colors,
autopct='%.0f%%',
explode = explode,
shadow = True,
startangle = 180)
ax.set_title('Survery responses')
plt.show()
Customizing Plot Legends

• The simplest legend can be created with the plt.legend() command,


which automatically creates a legend for any labeled plot elements:
Example
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
ax.legend(loc='upper left', frameon=False)
plt.show()
we can specify the location and turn off the
frame:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
ax.legend(loc='upper left', frameon=False)
plt.show()
We can use the ncol command to specify the
number of columns in the legend:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('classic')
x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
ax.legend(frameon=False, loc='lower center', ncol=2)
plt.show()
Customizing Colorbars
• Plot legends identify discrete labels of discrete points. For continuous labels based on the color of
points, lines, or regions, a labeled colorbar can be a great tool.
• In Matplotlib, a colorbar is a separate axes that can provide a key for the meaning of colors in a
plot.
• Syntax:matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kwarg)
• Parameters:
• ax: This parameter is an optional parameter and it contains Axes or list of Axes.
• **kwarg(keyword arguments): This parameter is an optional parameter and are of two kinds:
• colorbar properties:
• extend:{‘neither’, ‘both’, ‘min’, ‘max’} makes pointed end(s) for out-of-range
values.
• label:The label on the colorbar’s long axis.
• ticks:None or list of ticks or Locator.
• Returns:colorbar which is an instance of the class ‘matplotlib.colorbar.Colorbar’.
Colormaps in Matplotlib
Customizing Colorbars
# Python Program illustrating
# pyplot.colorbar() method
import matplotlib.pyplot as plt
# Dataset
# List of total number of items purchased
# from each products
purchaseCount = [100, 200, 150, 23, 30, 50,156, 32, 67, 89]
# List of total likes of 10 products
likes = [50, 70, 100, 10, 10, 34, 56, 18, 35, 45]
# List of Like/Dislike ratio of 10 products
ratio = [1, 0.53, 2, 0.76, 0.5, 2.125, 0.56,1.28, 1.09, 1.02]
# scatterplot
plt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer")
plt.colorbar(label="Like/Dislike Ratio", orientation="horizontal")
plt.show()
Customizing Colorbars
import matplotlib.pyplot as plt
rollno= [1,2,3,4,5,6,7,8,9,10]
marks= [30,28,22,18,15,5,0,19,22,23]
avgls=[]
for i in marks:
avg=i/30*100
avg="{:.2f}".format(avg)
avgls.append(float(avg))
print(avgls)
plt.scatter(x=rollno, y=marks, c=avgls, cmap="cool")
plt.colorbar(label="Percentage", orientation="horizontal")
plt.show()
Multiple Subplots
• Sometimes it is helpful to compare different views of data side by
side.
• To this end, Matplotlib has the concept of subplots: groups of smaller
axes that can exist together within a single figure.
• These subplots might be insets, grids of plots, or other more
complicated layouts.
Multiple Subplots
• For example, we might create an inset axes at the top-right corner of
another axes by setting the x and y position to 0.65 (that is, starting
at 65% of the width and 65% of the height of the figure) and
the x and y extents to 0.2 (that is, the size of the axes is 20% of the
width and 20% of the height of the figure):
import matplotlib.pyplot as plt
ax1 = plt.axes() # standard axes
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])
plt.show()
Multiple Subplots
• The equivalent of this command within the object-oriented interface is
fig.add_axes().
• Let's use this to create two vertically stacked axes:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4])
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4])
x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x))
plt.show()
Multiple Subplots
# importing packages
import matplotlib.pyplot as plt
import numpy as np
# making subplots objects
fig, ax = plt.subplots(2, 2)
# create data
x = np.linspace(0, 10, 1000)
# draw graph
ax[0, 0].plot(x, np.sin(x), 'r-.')
ax[0, 1].plot(x, np.cos(x), 'g--')
ax[1, 0].plot(x, np.tan(x), 'y-')
ax[1, 1].plot(x, np.sinc(x), 'c.-')
plt.show()
Text and Annotation
• The uses of the basic text() will place text at an arbitrary position on
the Axes
• The annotate() function in the pyplot module (or annotate method of
the Axes class) is used to draw an arrow connecting two points on
the plot.
• In an annotation, there are two points to consider: the location being
annotated represented by the argument xy and the location of the
text xytext. Both of these arguments are (x, y) tuples
• Example
Text and Annotation
• Optionally, you can enable drawing of an arrow from the text to the
annotated point by giving a dictionary of arrow properties in the
optional keyword argument arrowprops.
Annotating with Text with arrow
import matplotlib.pyplot as plt
import numpy as np
st=[1,2,3,4,5,6,7,8]
ls=[10,20,30,40,35,55,12,46]
mean=np.mean(ls)
print(mean)
f, ax = plt.subplots()
ax.plot(st,ls,"-b",label="Marks")
ax.annotate(('Mean',mean), xy=(4.5, 31.0), xytext=(5, 32),arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
Annotating with Text with Box
import matplotlib.pyplot as plt
import numpy as np
st=[1,2,3,4,5,6,7,8]
ls=[10,20,30,40,35,55,12,46]
mean=np.mean(ls)
print(mean)
f, ax = plt.subplots()
ax.plot(st,ls,"-b",label="Marks")
ax.annotate('Mean', xy=(4.5, 31.0), xytext=(5, 32),bbox=dict(boxstyle="rarrow,pad=0.3", fc="cyan", ec="b", lw=2))
plt.show()
Annotating with Text with Box
Customizing Ticks
• In Matplotlib library the Ticks are the markers that are used to
denote the data points on the axis.
• It is important to note that in the matplotlib library the task of
spacing points on the axis is done automatically.
• The default tick locators and formatters in matplotlib are also good
and are sufficient for most of the use-cases.
• This task can be done explicitly with the help of two functions:
set_xticks() and set_yticks()
• Both these functions will take a list object as its arguments. The
elements that are present in the list denote the positions and the
values that will be shown on these tick positions is set using the
set_xticklables() and set_yticklabels() functions.
Method 1: Using xticks() and yticks()
• Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
• Parameter:
• ticks – The list of x ticks.
• labels – The list of tick labels
• kwargs – Text effects on labels
• Returns:
• locs – The list of x ticks.
• labels – The list of tick text labels
Method 1: Using xticks() and yticks()
# Setting x and y values for the plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]
# Initiating the plot
plt.plot(x, y)
plt.title("PLOT")
# Setting the x and y labels
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
# Setting the number of ticks
plt.xticks([1, 2, 3, 4])
plt.yticks([7, 13, 24, 22])
# Showing the plot
plt.show()
Method 1: Using xticks() and yticks()
import numpy as np
import matplotlib.pyplot as plt
N=5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
#menStd = (2, 3, 4, 1, 2)
#womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, menMeans, width,label="Men")
p2 = plt.bar(ind, womenMeans, width,bottom=menMeans,label="Women")
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend()
plt.show()
Method 2: Using locator_param()
• syntax: matplotlib.pyplot.locator_params(axis=’both’, tight=None,
nbins=None **kwargs)
• Parameter:
• axis – The axis we need to change the number of ticks or tighten
them.
• tight – Takes in a bool value weather the ticks should be tightened or
not
• nbins – number of ticks we should have in the axis.
Method 2: Using locator_param()
# Setting x and y values for the plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]
# Initiating the plot
plt.plot(x, y, color='Red')
plt.title("PLOT")
# Setting the x and y labels
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
# Setting the number of ticks
plt.locator_params(axis='both', nbins=4)
# Showing the plot
plt.show()
Stylesheets
• The version 1.4 release of Matplotlib in August 2014 added a very
convenient style module, which includes a number of new default
stylesheets, as well as the ability to create and package your own
styles.
• These stylesheets are formatted similarly to the .matplotlibrc files
mentioned earlier, but must be named with a .mplstyle extension.
• Even if you don't create your own style, the stylesheets included by
default are extremely useful. The available styles are listed in
plt.style.available
• plt.style.available gives a list of all the available stylesheet option
names
Different Stylesheets
Matplotlib Stylesheets
• The ‘FiveThirtyEight Stylesheet-The ‘FiveThirtyEight Style is based on the popular American
blog FiveThirtyEight which provides economic, sports, and political analysis
• The ‘dark_background‘ stylesheet is another popular style that is based on the dark mode we see
today.
• The ‘grayscale’ stylesheet does not have involvement of any colour and thus got its name. This
stylesheet resembles the vintage black and white newspapers which do not have any colour in
them.The ‘cyberpunk’ Stylesheet
• The ‘cyberpunk‘ stylesheet is based on the popular fictional world of Cyberpunk. On applying this
style, the plot gets a dark blue grid background with neon coloured lines/bars.
• The tableau-colorblind10 Stylesheet is based on the widely used Business Intelligence tool
Tableau. Applying this style gives our plot the look of plots created in TableauThe ‘seaborn-
whitegrid’ Style
• We can use the preset of popular Seaborn library in our charts by using the ‘seaborn-whitegrid‘
stylesheet. As the name suggests, the stylesheet comes with a white background and grid thus
increases the readability of the plots.
Example on Stylesheets
import matplotlib.pyplot as plt
plt.style.use("fivethirtyeight")
a = [2, 3, 4, 3, 4, 5, 3]
b = [4, 5, 5, 7, 9, 8, 6]
c = [1, 3, 9, 5, 2, 1, 1]
plt.figure(figsize = (20,8))
plt.plot(a, marker='o')
plt.plot(b, marker='v')
plt.plot(c, marker='s')
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.show()
The ‘dark_background’ Stylesheet
import matplotlib.pyplot as plt
plt.style.use("dark_background")
a = [2, 3, 4, 3, 4, 5, 3]
b = [4, 5, 5, 7, 9, 8, 6]
c = [1, 3, 9, 5, 2, 1, 1]
plt.figure(figsize = (20,8))
plt.plot(a, marker='o')
plt.plot(b, marker='v')
plt.plot(c, marker='s')
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.show()
The ‘grayscale’ Stylesheet
import matplotlib.pyplot as plt
plt.style.use("grayscale")
a = [2, 3, 4, 3, 4, 5, 3]
b = [4, 5, 5, 7, 9, 8, 6]
c = [1, 3, 9, 5, 2, 1, 1]
plt.figure(figsize = (20,8))
plt.plot(a, marker='o')
plt.plot(b, marker='v')
plt.plot(c, marker='s')
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.show()
Three-Dimensional Plotting in Matplotlib
• Matplotlib was initially designed with only two-dimensional plotting
in mind. Around the time of the 1.0 release, some three-dimensional
plotting utilities were built on top of Matplotlib's two-dimensional
display, and the result is a convenient (if somewhat limited) set of
tools for three-dimensional data visualization.
• Three-dimensional plots are enabled by importing the mplot3d
toolkit, included with the main Matplotlib installation:
Example
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
plt.show()
Example
# importing matplotlib package
import matplotlib.pyplot as plt
# creating an empty canvas
fig = plt.figure()
# defining the axes with the projection
ax = plt.axes(projection="3d")
# creating a wide range of points x,y,z
x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 1, 4, 9, 16, 25, 36]
# plotting a 3D line graph with X-coordinate,
ax.plot3D(x, y, 'red')
ax.scatter3D(x, y, marker='o')
# Showing the above plot
plt.show()

You might also like