SE Matplotlib
SE Matplotlib
1
[ ]: import pandas as pd
df = pd.read_csv("/home/mymate/UDM/Modules/Python_Introduction to Data Science/
↪Datasets/iris.csv")
# titanic.csv
df.head()
1 LINE PLOT
Example 1
[ ]: # Python Program to illustrate Linear Plotting
import matplotlib.pyplot as plt
plt.legend()
plt.show()
[ ]:
Example 2
[ ]: # Python Program to illustrate Linear Plotting
import matplotlib.pyplot as plt
2
# year contains the x-axis values
# and e-india & e-bangladesh
# are the y-axis values for plotting
plt.legend()
plt.show()
[ ]:
plt.stem(x, y)
plt.show()
[ ]:
3
3 BAR CHART
[ ]: titanic = pd.read_csv("/home/mymate/UDM/Modules/Python_Introduction to Data␣
↪Science/Datasets/titanic.csv")
[ ]: titanic.columns
plt.show()
plt.show()
[ ]:
4 HISTOGRAM
[ ]: iris = pd.read_csv("/home/mymate/UDM/Modules/Python_Introduction to Data␣
↪Science/Datasets/iris.csv")
iris.columns
version 1
[ ]: # plotting histograms
plt.hist(iris['petal.length'], label='petal length')
4
plt.hist(iris['sepal.length'], label='sepal length')
plt.legend(loc='upper right')
plt.title('Overlapping')
plt.show()
version 2 - Transparency parameter ‘alpha’ Play around by changing the alpha value for
both sepal length and petal length
[ ]: # plotting histograms
plt.hist(iris['petal.length'], label='petal length', alpha = 0.5)
plt.legend(loc='upper right')
plt.title('Overlapping')
plt.show()
plt.legend(loc='upper right')
plt.show()
[ ]:
5
Subplots in Matplotlib Using 1-D Array of Subplots Matplotlib generates a figure with
two subplots.
The data, represented by arrays ‘x,’ ‘y,’ and ‘z,’ is plotted on separate axes within the figure.
The resulting visualization displays distinct plots for the datasets ‘y’ and ‘z’ in the designated
subplots
[ ]: # importing library
import matplotlib.pyplot as plt
# Creating 2 subplots
fig, ax = plt.subplots(2)
# Accessing each axes object to plot the data through returned array
ax[0].plot(x, y)
ax[1].plot(x, z)
[ ]:
Matplotlib Multiple Plots Same Figure Matplotlib creates a 2×2 grid of subplots.
Each subplot showcases a different type of plot: line plot, scatter plot, bar plot, and histogram.
The Axes objects are accessed through the 2D array ‘axs,’ and specific data is visualized in each
subplot, demonstrating the flexibility of Matplotlib for diverse plotting needs.
[ ]: # Create a 2x2 grid of subplots
fig, axs = plt.subplots(2, 2)
6
# Now axs is a 2D array of Axes objects
axs[0, 0].plot([1, 2, 3], [4, 5, 6])
axs[0, 1].scatter([1, 2, 3], [4, 5, 6])
axs[1, 0].bar([1, 2, 3], [4, 5, 6])
axs[1, 1].hist([1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5])
plt.show()
5 VIOLIN PLOT
[ ]: iris.columns
[ ]: len(iris)
[ ]: iris['variety'].value_counts()
[ ]: plt.violinplot( iris['sepal.length'] )
[ ]:
[ ]: iris_petalLength = iris[['petal.length','variety']]
[ ]: iris_petalLength['variety'].value_counts()
[ ]: #plt.figure(figsize=(12,8))
plt.subplot(2,2,1)
plt.violinplot( iris_petalLength_setosa['petal.length'] )
plt.subplot(2,2,2)
plt.violinplot(iris_petalLength_versicolor['petal.length'] )
plt.subplot(2,2,3)
plt.violinplot(iris_petalLength_virginica['petal.length'] )
[ ]:
7
6 BOXPLOT
version 1
[ ]: plt.subplot(2,2,1)
plt.boxplot( iris_petalLength_setosa['petal.length'] )
plt.subplot(2,2,2)
plt.boxplot(iris_petalLength_versicolor['petal.length'] )
plt.subplot(2,2,3)
plt.boxplot(iris_petalLength_virginica['petal.length'] )
[ ]:
•
– is your data.
•
•
– sets the plot orientation to horizontal when False. The default orientation is vertical.
•
•
– shows the mean of your data when True.
•
•
– represents the mean as a line when True. The default representation is a point.
•
•
– the labels of your data.
•
•
– determines how to draw the graph.
•
8
•
– denotes the properties of the line representing the median.
•
•
– indicates the properties of the line or dot representing the mean.
[ ]:
[ ]: fig, ax = plt.subplots()
ax.boxplot( (iris_petalLength_setosa['petal.length'],␣
↪iris_petalLength_versicolor['petal.length'],␣
↪iris_petalLength_virginica['petal.length']),
showmeans=True, meanline=True,
labels=('Setosa', 'Versicolor', 'Virginica'), patch_artist=True,
medianprops={'linewidth': 2, 'color': 'purple'},
meanprops={'linewidth': 2, 'color': 'red'} )
ax.set_xlabel('Variety of Iris')
ax.set_ylabel('Petal Length')
plt.show()
[ ]:
[ ]:
7 SCATTER PLOT
[ ]:
Example 1
[ ]: import matplotlib.pyplot as plt
x = df['petal.length']
y = df['sepal.length']
9
plt.title('Scatter Plot with Color Mapping')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()
[ ]:
Example 2
[ ]: versicolor = df[ df["variety"]== "Versicolor" ]
setosa = df[ df["variety"] == "Setosa" ]
virginica = df[ df["variety"] == "Virginica" ]
fig, ax = plt.subplots()
fig.set_size_inches(8, 8)
[ ]:
8 PIE CHART
version 1
[ ]: from matplotlib import pyplot as plt
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']
# Creating plot
#fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)
10
# show plot
plt.show()
[ ]:
version 2
[ ]: iris_flowers = ['SETOSA', 'VERTICOLOR', 'VIRGINICA']
# DATA
versicolor = iris[ iris["variety"]== "Versicolor" ]
setosa = df[ df["variety"] == "Setosa" ]
virginica = df[ df["variety"] == "Virginica" ]
# Creating plot
#fig = plt.figure(figsize=(10, 7))
setosa_sumPetalLength = setosa['petal.length'].sum()
versicolor_sumPetalLength = versicolor['petal.length'].sum()
virginica_sumPetalLength = virginica['petal.length'].sum()
plt.pie(data, labels=iris_flowers)
# show plot
plt.show()
[ ]:
version 3
[ ]: iris_flowers = ['SETOSA', 'VERTICOLOR', 'VIRGINICA']
# DATA
versicolor = iris[ iris["variety"]== "Versicolor" ]
setosa = df[ df["variety"] == "Setosa" ]
virginica = df[ df["variety"] == "Virginica" ]
# Creating plot
#fig = plt.figure(figsize=(10, 7))
setosa_sumPetalLength = setosa['petal.length'].sum()
versicolor_sumPetalLength = versicolor['petal.length'].sum()
virginica_sumPetalLength = virginica['petal.length'].sum()
11
data = [setosa_sumPetalLength, versicolor_sumPetalLength,␣
↪virginica_sumPetalLength ]
fig, ax = plt.subplots()
ax.pie( data, labels=iris_flowers, autopct='%1.1f%%' )
ax.set_title("Pie Chart showcasing the sum of Petal Length for the 3 IRIS␣
↪Varieties")
plt.show()
[ ]:
12