Python4_Papia
Python4_Papia
Graphical plot
Introduce to graphing in python with Matplotlib,
which is arguably the most popular graphing and data
visualization library for Python.
The easiest way to install matplotlib is to use pip. Type
following command in terminal:
pip install matplotlib
1
5/27/2023
2
5/27/2023
Output:
3
5/27/2023
4
5/27/2023
Output
Customization of Plots
mport matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)
5
5/27/2023
Output
6
5/27/2023
Bar Chart
import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1, 2, 3, 4, 5]
# heights of bars
height = [10, 24, 36, 40, 5]
# labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']
# plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])
7
5/27/2023
Output
Histogram
plt.hist() function is used to plot a histogram.
8
5/27/2023
Histogram
import matplotlib.pyplot as plt
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]
# setting the ranges and no. of intervals
range = (0, 100)
bins = 10
# plotting a histogram
plt.hist(ages, bins, range, color = 'green',
histtype = 'bar', rwidth = 0.8)
# x-axis label
plt.xlabel('age')
# frequency label
plt.ylabel('No. of people')
# plot title
plt.title('My histogram')
# function to show the plot
plt.show()
9
5/27/2023
Output
Scatter plot
plt.scatter() function is used to plot a scatter plot.
10
5/27/2023
# x-axis label
plt.xlabel('x - axis')
# frequency label
plt.ylabel('y - axis')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()
# function to show the plot
plt.show()
11
5/27/2023
output
12
5/27/2023
Pie-chart
import matplotlib.pyplot as plt
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# portion covered by each label
slices = [3, 7, 8, 6]
# color for each label
colors = ['r', 'y', 'g', 'b']
# plotting the pie chart
plt.pie(slices, labels = activities, colors=colors,
startangle=90, shadow = True, explode = (0, 0, 0.1, 0),
radius = 1.2, autopct = '%1.1f%%')
# plotting legend
plt.legend()
# showing the plot
plt.show()
13
5/27/2023
Output
14
5/27/2023
output
15
5/27/2023
Subplots
Subplots are required when we want to show two or
more plots in same figure. We can do it in two ways
using two slightly different methods.
16
5/27/2023
17
5/27/2023
output
18