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

Matplolib Cheat Sheet v2

Uploaded by

Athira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Matplolib Cheat Sheet v2

Uploaded by

Athira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Matplotlib Cheat Sheet

Import Libraries and Create a DataFrame Line Plot (Object Oriented Method)
import numpy as np fig, ax= plt.subplots()
import pandas as pd ax.plot(df.men_age, df.men_salary ,"b")
import seaborn as sns ax.set_xlabel("men age")
import matplotlib.pyplot as plt ax.set_ylabel("men salary", color="r")
men_age = [25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45] ax.set_title("salary by age", color="b")
men_salary = [38496, 42000, 46752, 49320, 53200, ax.axvline(x=35, color="red", ls="--") # creating a vertical line for a given "x"
56000, 62316, 64928, 67317, 68748, 73752] value
women_salary = [45372, 48876, 53850, 57287, 63016,
65998, 70003, 70000, 71496, 75370, 83640]
women_age =[22, 26, 28, 30, 33, 37, 38, 39, 42, 43, 44]
group=["G1", "G2","G3","G4","G5","G6","G7","G8","G9","G10","G11"]
df=pd.DataFrame({"men_age":men_age, "men_salary":men_salary,
"women_age":women_age, "women_salary":women_salary, "group":group})

Line Plot (Functional Method)


plt.plot(df.men_age, df.men_salary, marker="o", label="men") # label is required
for legend
plt.plot(df.women_age, df.women_salary, marker="+", ls="--", color="r",
label="women")
plt.xlabel("age")
plt.ylabel("salary")
plt.title("salary by age")
Setting x_lim and y_lim
plt.legend()
fig, ax= plt.subplots()
ax.plot(df.men_age, df.men_salary ,"b")
ax.set_xlabel("men age")
ax.set_ylabel("men salary", color="r")
ax.set_title("salary by age", color="b")
ax.set_xlim([30,40]) # focusing on the given x values
ax.set_ylim([50000,65000]) # focusing on the given y values

Subplots (Fuctional Method)


plt.figure(figsize=(6, 6))
plt.subplot(2,1,1) # nrow=2, ncols=1, index=1
plt.plot(df.men_age, df.men_salary, label="men", color="b")
plt.title("salary by age")
Subplots (Object Oriented Method)
plt.ylabel("salary") fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,3))
plt.xlabel("age") ax[0].plot(df.men_age, df.men_salary ,color="b", lw="3", ls="-.")
plt.legend(loc=0) # loc=0 determines best location for the legend ax[0].set_title("salary by age-men")
plt.subplot(2,1,2) ax[1].plot(df.women_age, df.women_salary ,color="r", lw="2", ls="dashed")
plt.plot(df.women_age, df.women_salary, label="women", color="r") ax[1].set_title("salary by age-women")
plt.xlabel("age") plt.tight_layout()
plt.ylabel("salary")
plt.legend(loc=4) # loc=4 puts the legend to bottom right
plt.tight_layout() # to fit the subplots.
Scatter Plot Bar Plot (Not Stacked)
fig,ax=plt.subplots() x=np.arange(len(df.group))
ax.scatter(df.men_age, df.men_salary, color="blue", label="men") width=0.4
ax.scatter(df.women_age, df.women_salary, color="red", label="women") fig,ax=plt.subplots(figsize=(12,6))
ax.set_xlabel("Age") ax.bar(x - width/2, df.men_age, width, label='Men')
ax.set_ylabel("Salary") ax.bar(x + width/2, df.women_age, width, label='Women')
ax.legend(loc=9) # legend at the top center ax.set_xticks(x)
ax.set_xlabel("Groups")
ax.set_ylabel("Ages")
ax.set_title("Age groups by gender")
ax.axhline(y=25, color="red", ls="--") # adds a horizontal line for a given "y"
value
ax.legend()
ax.set_xticklabels(df.group) #labelling the bars
# to annotate numbers
for p in ax.patches:
ax.annotate((p.get_height()), (p.get_x()+0.05, p.get_height()+1))

Bar Plot
fig,ax=plt.subplots(figsize=(8,5))
ax.bar(df.group, df.men_salary)
ax.set_xlabel("Age Groups")
ax.set_ylabel("Salary")
ax.set_title("Salary by Age Groups")

Pie Chart
slices = [59000, 55000, 47000, 36000, 35000]
langs = ['JavaScript', 'HTML/CSS', 'SQL', 'Python', 'Java']
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = langs
sizes = slices
explode = (0, 0, 0, 0.2, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
fig, ax = plt.subplots(figsize=(7,7))
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=False, startangle=110)
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()

Bar Plot (Stacked)


fig,ax=plt.subplots(figsize=(12,6))
ax.bar(df.group, df.men_age, label="men")
ax.bar(df.group, df.women_age, bottom=df.men_age, label="women")
ax.set_xlabel("Groups")
ax.set_ylabel("Ages")
ax.set_title("Age groups by gender")
ax.legend()
Box Plot (With Subplots) Box Plot (On the same axes)
fig,ax=plt.subplots(1,2, figsize=(7,4)) fig,ax=plt.subplots()
ax[0].boxplot(df.women_salary) ax.boxplot([df.women_salary, df.men_salary])
ax[0].set_xlabel("Women Salary") ax.set_xticklabels(["Women Salary", "Men Salary"])
ax[1].boxplot(df.men_salary) ax.set_ylabel("Salary")
ax[1].set_xlabel("Men Salary")
plt.tight_layout()

Histogram
tips=sns.load_dataset("tips")
fig,ax=plt.subplots()
ax.hist(tips.total_bill, bins=15, edgecolor="black", color="green")

Matplotlib is a comprehensive library for creating static, animated, and


interactive visualizations in Python.
Matplotlib ships with several add-on toolkits, including 3D plotting with
mplot3d, axes helpers in axes_grid1 and axis helpers in axisartist.
For more information please visit https://matplotlib.org/.

You might also like