Intro to MatPlotLib

Created
Tags

Indroduction

from matplotlib import pyplot as plt

plt.plot(x_num, y_num) # fucking format is y vs. x
plt.show()

plt.plot(<x>, <y>, colour = <''>, linestyle = <':', '--'>, marker = <'s', 'o', '*'>)

plt.axis([x_min, x_max, y_min, y_max])

Subplots

# Left Plot
plt.subplot(1, 2, 1)
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])

# Right Plot
plt.subplot(1, 2, 2)
plt.plot([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])

# Subplot Adjust options are - left, right, bottom, top, wspace, hspace
plt.subplots_adjust(wspace=0.35) 

plt.show()


# Better Approach
fig, axs = plt.subplots(2, 2)
axs[0, 0].hist(dist_1)
axs[0, 1].hist(dist_2)
axs[1, 0].hist(dist_3)
axs[1, 1].hist(dist_4)
plt.show()

Legends

# legend_labels is a list
plt.legend(legend_labels)

# alternate example
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16],
         label="parabola")
plt.plot([0, 1, 2, 3, 4], [0, 1, 8, 27, 64],
         label="cubic")
plt.legend() # Still need this command!
plt.show()

Modify Ticks

# This explains the working
ax = plt.subplot()
ax.set_xticks([<values>])
ax.set_yticks

# Further Example
ax = plt.subplot()
ax.set_xticks(months)
ax.set_xticklabels(month_names)
ax.set_yticks([0.10, 0.25, 0.5, 0.75])
ax.set_yticklabels(["10%", "25%", "50%", "75%"])

Figures

# Figure
plt.figure(figsize=(4, 10))
plt.plot(x, parabola)
plt.savefig('tall_and_narrow.png')

Simple Bar Chart

plt.bar() # instead of plt.plot()

n = ?  # This is our dataset
t = ? # Number of datasets
d = ? # Number of sets of bars
w = ? # Width of each bar
x_values = [t*element + w*n for element
             in range(d)]
# The above explains the idea of forming side-by-side bars

# Forming Stacked Bar Charts
plt.bar(range(len(drinks)), sales1)
plt.bar(range(6), sales2, bottom = sales1)