import matplotlib.pyplot as plt
import numpy as np
# Sample data - generating random data points using normal distribution
np.random.seed(0)
x = np.random.randn(1000)
y = np.random.randn(1000)
colors = np.random.randint(10, 101, size=1000)
sizes = np.random.randint(10, 101, size=1000)
# Scatter plot with multiple customizations
plt.scatter(x, y, c=colors, cmap="viridis", s=sizes, marker='o', alpha=0.5)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter Plot with Matplotlib')
plt.show()Matplotlib draws charts from Python code: line and bar charts, scatter plots, histograms, pie charts and many more. It saves them as PNG, SVG or PDF files, and pandas and seaborn draw their charts with it. People use it for figures in reports, papers and homework, and to explore data. This page is an online Matplotlib compiler: the code runs in your browser, so you can try it without installing anything. Run the example first, then paste any snippet below into a new cell to try it.
np.random.seed(0) fixes the random numbers, so every run draws the
same chart. np.random.randn(1000) gives 1,000 values from a standard
normal distribution for each axis.
np.random.randint(10, 101, size=1000) gives 1,000 whole numbers from
10 to 100, once for the colours and once for the sizes. plt.scatter()
draws one marker per point: c=colors with cmap="viridis" maps each
number to a colour from dark purple to yellow, s=sizes sets each
marker's area in points squared, and alpha=0.5 makes the markers half
transparent, so overlapping points stay visible. plt.xlabel(),
plt.ylabel() and plt.title() add the text, and plt.show() displays
the chart below the cell.
Most Matplotlib code starts with plt.subplots(), which returns a
figure and an axes to draw on. Give each line a label, and
ax.legend() lists them:
import matplotlib.pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
online = [120, 135, 150, 145, 170, 190]
in_store = [200, 180, 175, 160, 150, 140]
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(months, online, marker="o", label="Online")
ax.plot(months, in_store, marker="s", linestyle="--", color="gray", label="In store")
ax.set_title("Monthly sales")
ax.set_xlabel("Month")
ax.set_ylabel("Units sold")
ax.legend()
ax.grid(alpha=0.3)
plt.show()
figsize is the width and height in inches. marker, linestyle and
color change how each line looks.
plt.subplots(1, 3) returns one row of three axes, and each can hold a
different chart type:
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(seed=1)
heights = rng.normal(170, 8, size=500)
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4))
bars = ax1.bar(["A", "B", "C", "D"], [23, 17, 35, 29], color="tab:green")
ax1.bar_label(bars)
ax1.set_ylim(0, 40)
ax1.set_title("Bar chart")
ax2.hist(heights, bins=20, edgecolor="white")
ax2.set_title("Histogram")
ax3.pie([45, 30, 25], labels=["Rent", "Food", "Other"], autopct="%1.0f%%")
ax3.set_title("Pie chart")
fig.suptitle("Three chart types")
plt.show()
bar_label() writes each bar's value on top of it, and autopct prints
each slice's share. plt.subplots(2, 2) returns a grid instead, and
axes[0, 1] is its top-right chart.
A style sets colours, backgrounds and grid lines.
plt.style.available lists the built-in ones, and
plt.style.context() applies one only inside the with block:
import matplotlib.pyplot as plt
print(plt.style.available)
with plt.style.context("ggplot"):
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3, 4, 5, 6], [2, 4, 3, 6, 5, 8], marker="o", label="Team A")
ax.plot([1, 2, 3, 4, 5, 6], [1, 3, 4, 4, 6, 7], marker="o", label="Team B")
ax.set_title("ggplot style")
ax.legend()
plt.show()
plt.style.use("ggplot") applies it to every chart after it, until you
call plt.style.use("default").
fig.savefig() writes the figure to a file, and the extension sets the
format. dpi sets the resolution of a PNG, and bbox_inches="tight"
trims the empty margin. The files appear in the sidebar's Data tab:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(["Q1", "Q2", "Q3", "Q4"], [120, 135, 150, 170])
ax.set_title("Quarterly sales")
fig.savefig("sales.png", dpi=200, bbox_inches="tight")
fig.savefig("sales.svg", bbox_inches="tight")
fig.savefig("sales.pdf")
plt.show()
plt.savefig() clears the figure once the file is
written, so a plt.show() after it displays an empty chart.
fig.savefig() leaves the figure as it is.plt.plot() without plt.show() shows
[<matplotlib.lines.Line2D object at ...>] instead of a chart, and
that line then turns up in the next chart you show.