How AlmaBetter created an
IMPACT!Arunav Goswami
Data Science Consultant at almaBetter
Learn key Matplotlib functions with our Matplotlib cheat sheet. Includes examples, advanced customizations and comparison with Seaborn for better visualizations
Matplotlib is a versatile library in Python used for data visualization. Matplotlib enables the creation of static, interactive, and animated visualizations in Python. It is highly customizable and integrates well with libraries like Pandas and NumPy. Its pyplot module simplifies the process of creating plots similar to MATLAB. This Matplotlib cheat sheet provides an overview of the essential functions, features, and tools available in Matplotlib, along with comparisons to Seaborn where relevant.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(width, height))
plt.show()
fig, axs = plt.subplots(nrows, ncols, figsize=(width, height))
Use axs as a 2D array for multiple subplots:
axs[row, col].plot(x, y)
plt.tight_layout()
fig.suptitle('Main Title', fontsize=16)
plt.plot(x, y, label='Label', color='blue', linestyle='-', marker='o')
Parameters:
plt.scatter(x, y, c='red', s=40, alpha=0.5, label='Label')
plt.bar(categories, values, color='green', alpha=0.7, label='Label')
plt.barh(categories, values, color='purple', alpha=0.7, label='Label')
plt.hist(data, bins=10, color='gray', alpha=0.8, label='Histogram')
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
Optional Parameters:
plt.boxplot(data, vert=True, patch_artist=True)
plt.imshow(data, cmap='viridis', interpolation='nearest')
ax.set_title('Title')
ax.set_xlabel('X-axis Label')
ax.set_ylabel('Y-axis Label')
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
ax.grid(True, which='both', linestyle='--', linewidth=0.5)
ax.set_xticks([x1, x2, x3])
ax.set_yticks([y1, y2, y3])
plt.xticks(rotation=45)
ax.legend(loc='upper right', fontsize='small')
loc: 'upper left', 'upper right', 'lower left', 'lower right'
ax.text(x, y, 'Text', fontsize=12, color='red', ha='center', va='center')
ax.annotate('Annotation', xy=(x, y), xytext=(x_text, y_text),
arrowprops=dict(facecolor='black', shrink=0.05))
plt.style.use('ggplot')
Popular styles: 'seaborn', 'fivethirtyeight', 'classic'
plt.savefig('filename.png', dpi=300, bbox_inches='tight')
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(x, y, z, color='blue')
ax.scatter3D(x, y, z, c=z, cmap='Greens')
ax.set_xscale('log')
ax.set_yscale('log')
ax2 = ax.twinx()
ax2.plot(x, y, color='green')
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y, 'g-')
ax2.plot(x, np.cos(x), 'b--')
from matplotlib import cm
cmap = cm.get_cmap('viridis')
plt.scatter(x, y, c=z, cmap=cmap)
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlabel("X")
ax.set_ylabel("Y")
plt.show()
Function | Purpose |
---|---|
plt.figure() | Create a new figure. |
plt.subplots() | Create subplots within a figure. |
plt.show() | Display the current figure. |
plt.savefig('filename') | Save the figure to a file. |
plt.errorbar() | Add error bars to data points. |
import pandas as pd
df = pd.DataFrame({'x': range(10), 'y': range(10)})
df.plot(x='x', y='y', kind='line')
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
import seaborn as sns
sns.set(style='whitegrid') # Set a seaborn style
Feature | Matplotlib | Seaborn |
---|---|---|
Customization | High | Medium |
Ease of Use | Moderate | High |
Integration | Standalone, supports Pandas | Built on Matplotlib, requires Pandas |
Plot Types | Basic and Customizable | Advanced statistical plots |
Matplotlib remains a cornerstone of data visualization in Python due to its flexibility and depth. By mastering its essential functions and understanding its integration with libraries like Pandas and Seaborn, users can create compelling visualizations for various datasets.
More Cheat Sheets and Top Picks