Fall 2023
Junehyung Lee
To install the python library, matplotlib, type below line to your terminal.
python -m pip install matplotlib
To load the installed python libary: (include this line before use plt
in the script)
import matplotlib.pyplot as plt
To initiate an empty figure with single ax and a size of 8" x 6":
fig, ax = plt.subplots(figsize=(8, 6))
To initiate an empty figure with multiple axes
(e.g., 6 axes with 2 x 3 layout):
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(8, 6))
"mtcars" dataset has been used for the following examples. The dataset also can be obtained at this url.
import pandas as pd
data = pd.read_csv('mtcars.csv')
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(x=data['Weight'], y=data['MPG'])
plt.tight_layout()
plt.show()
plt.savefig('mtcars-wt_mpg.png', dpi=300)
plt.close() # Run this line to close the plot.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 3))
ax.scatter(x=data['Weight'], y=data['MPG'])
ax.set_xlabel('Weight of vehicle (per 1,000 lbs)')
ax.set_ylabel('Milers per gallon (mpg)')
ax.tick_params(axis='both', labelsize=15)
plt.tight_layout()
plt.show()
plt.savefig('mtcars-wt_mpg-with labels.png', dpi=300)
Let's say we want to plot them in differnet colors based on whether its engine is V-shape or not.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 3))
ax.scatter(x=data['Weight'], y=data['MPG'], label=data['V-shape'])
ax.set_xlabel('Weight of vehicle (per 1,000 lbs)')
ax.set_ylabel('Milers per gallon (mpg)')
ax.tick_params(axis='both', labelsize=15)
plt.tight_layout()
plt.show()
plt.savefig('mtcars-wt_mpg-with labels.png', dpi=300)