Home β€Ί Curriculum β€Ί Data Visualisation
Updated for Python 3.12+ Β· November 2026

πŸ“Š Data Visualisation
in Python

Learn Python data visualisation: Matplotlib line, bar, scatter and histogram charts, subplots, labels and saving, plus how Seaborn and Plotly fit in.

Intermediate 9 lessonsβ‰ˆ 44 min read by Glenn Pansensoy

What this lesson is about

A table of numbers rarely tells you what is going on; a chart usually does. A line shows a trend, a bar chart compares categories, a scatter plot reveals whether two measurements move together, and a histogram shows the shape of a distribution. Data visualisation is how analysts spot mistakes in data, explain results to other people and decide what to investigate next.

In Python the foundation is Matplotlib. It is verbose compared with some newer tools, but it is everywhere: Pandas plots through it, Seaborn is built on top of it, and a huge number of tutorials and scientific papers use it. Once you understand its two core objects, the Figure (the whole canvas) and the Axes (one plot on that canvas), the rest is a matter of learning which method draws which chart.

This page runs real Matplotlib code in your browser, so you can press Run and see the picture straight away. I teach the object-oriented style, fig, ax = plt.subplots(), because it scales from one chart to a dashboard of many. The last two sections cover Seaborn and Plotly. Those need extra packages that do not run inside the browser, so I show them as code to run on your own computer and explain when you would choose them.

What you will learn

  • βœ“Explain the difference between a Figure and an Axes, and why plt.subplots() is the best starting point
  • βœ“Draw line, bar, scatter and histogram charts and know which question each one answers
  • βœ“Add titles, axis labels, legends, grid lines and annotations that make a chart readable
  • βœ“Arrange several charts together with subplots and keep their scales honest
  • βœ“Control colours, markers, line styles and figure size
  • βœ“Save a chart to a PNG file or an in-memory buffer with savefig
  • βœ“Draw a heatmap, and see how Seaborn shortens common statistical charts
  • βœ“Know when an interactive Plotly chart is a better choice than a static image

Why programmers should learn this

  • β˜…Charts catch data problems that summary statistics hide: outliers, impossible values and odd gaps are obvious in a plot and invisible in an average.
  • β˜…Communicating results is part of every data job. A clear, honestly labelled chart persuades far better than a table, and it is the thing colleagues actually remember.
  • β˜…Matplotlib is the base layer for much of the Python data world, so knowing it makes Pandas plotting, Seaborn and many scientific libraries easier to understand and customise.
  • β˜…Plots are automatable. A script that regenerates a report chart every week from fresh data saves the manual work of redrawing it in a spreadsheet.
  • β˜…Machine-learning work depends on plots, such as loss curves, residuals and confusion matrices, so this skill carries straight into the scikit-learn lesson.

Figure and Axes: the anatomy of a plot

Matplotlib draws onto a Figure, which is the whole window or image, and one or more Axes, which are the actual plotting areas with their own x and y scales. Confusingly, 'Axes' is one plot, not the plural of 'axis'. Each Axes holds the data, the tick marks, the labels and the title.

The recommended pattern is fig, ax = plt.subplots(). It creates a Figure and one Axes and hands you both. You then call methods on ax, such as ax.plot(...), ax.set_title(...) and ax.set_xlabel(...). There is also a quicker, state-based interface (plt.plot, plt.title) that works on whatever plot is 'current'. It is fine for a quick look, but I teach the object-oriented form because it stays clear when you have several plots.

Finally plt.show() displays the figure. On this page the picture appears under the code. Before you run the next example, take a moment to read the code and predict what the picture will contain: one line, rising, with a title and two labelled axes.

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 3, 6, 8]

fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(x, y)
ax.set_title("My first chart")
ax.set_xlabel("Day")
ax.set_ylabel("Visitors")
print(type(fig).__name__, type(ax).__name__)
plt.show()
Expected output
Figure Axes

Line by line

  1. 1Import the plotting module under its usual name plt.
  2. 3-4Two lists of the same length: the x positions and the y values.
  3. 6Create a Figure and one Axes. figsize=(5, 3) sets the size in inches (width, height).
  4. 7Draw a line connecting the points on the Axes.
  5. 8-10Give the chart a title and label both axes so a reader knows what the numbers mean.
  6. 11Print the class names to confirm what fig and ax are.
  7. 12Display the figure.
πŸ’‘

Always label axes with a quantity and, where it applies, a unit, such as 'Temperature (C)'. A chart without labels forces the reader to guess.

Line charts: trends over time

A line chart connects points in order, so it suits data that has a natural sequence such as time. Call ax.plot(x, y) once per line and give each a label= so a legend can name them. The lines share the same Axes, which makes comparison easy.

Style is controlled with small keyword arguments: color, linestyle ('-', '--', ':'), linewidth and marker ('o', 's', '^'). A marker on each point is helpful when you have few points, because it shows exactly where the real measurements are rather than implying continuous data between them.

To make the example deterministic and realistic, I use NumPy to generate two smooth series. Call ax.legend() after the lines have labels, and ax.grid(True, alpha=0.3) for light guide lines that help the eye without dominating the chart.

python
import numpy as np
import matplotlib.pyplot as plt

days = np.arange(1, 11)
plan_a = 100 + 8 * days
plan_b = 100 + 3 * days + 0.9 * days ** 2

fig, ax = plt.subplots(figsize=(6, 3.5))
ax.plot(days, plan_a, marker="o", label="Plan A (linear)")
ax.plot(days, plan_b, marker="s", linestyle="--", label="Plan B (growing)")
ax.set_title("Two growth plans")
ax.set_xlabel("Day")
ax.set_ylabel("Users")
ax.grid(True, alpha=0.3)
ax.legend()
print(int(plan_a[-1]), round(float(plan_b[-1]), 1))
plt.show()
Expected output
180 220.0

Line by line

  1. 4Days 1 to 10 as a NumPy array.
  2. 5-6Plan A grows by a fixed amount each day. Plan B has a squared term, so it starts slower and then overtakes.
  3. 8-9Draw each line with a marker and a label for the legend; plan B uses a dashed style.
  4. 10-12Title and axis labels.
  5. 13Faint grid lines; alpha is transparency from 0 to 1.
  6. 14Draw the legend from the labels given earlier.
  7. 15Print the final value of each plan to confirm the numbers behind the picture.

Bar charts: comparing categories

Use a bar chart when the x values are categories rather than a continuous scale: sales per region, errors per module, votes per option. ax.bar(names, values) draws vertical bars and ax.barh(...) draws horizontal ones, which is more readable when category names are long.

Honest bar charts start at zero. Bar length encodes the value, so if you cut off the bottom of the axis a small difference looks like a huge one. Lines and scatter plots can zoom in on a range, but bars should not.

Sorting the bars by value usually makes the message clearer than alphabetical order. You can also write the value on each bar with ax.bar_label(bars), which saves the reader from squinting at the axis. Grouped bars, where several series sit side by side, are made by shifting the x positions with NumPy.

python
import numpy as np
import matplotlib.pyplot as plt

regions = ["North", "South", "East", "West"]
q1 = [120, 95, 140, 80]
q2 = [130, 110, 125, 105]

order = np.argsort(q2)[::-1]
names = [regions[i] for i in order]
q2_sorted = [q2[i] for i in order]
print(names, q2_sorted)

fig, (left, right) = plt.subplots(1, 2, figsize=(8, 3.2))
bars = left.bar(names, q2_sorted, color="#3b7dd8")
left.bar_label(bars)
left.set_title("Q2 sales, sorted")
left.set_ylabel("Units")

pos = np.arange(len(regions))
width = 0.38
right.bar(pos - width / 2, q1, width, label="Q1")
right.bar(pos + width / 2, q2, width, label="Q2")
right.set_xticks(pos)
right.set_xticklabels(regions)
right.set_title("Q1 vs Q2")
right.legend()
fig.tight_layout()
plt.show()
Expected output
['North', 'East', 'South', 'West'] [130, 125, 110, 105]

Line by line

  1. 4-6Four regions with two quarters of sales.
  2. 8-10argsort gives the order that sorts Q2 ascending; reversing it puts the biggest first. Rebuild the names and values in that order.
  3. 11Print the sorted result.
  4. 13Create one Figure with two Axes side by side, named left and right.
  5. 14-17Left chart: sorted bars, a value label on each bar, a title and a y label.
  6. 19-20For grouped bars, compute x positions and a bar width.
  7. 21-22Draw Q1 shifted left of each position and Q2 shifted right.
  8. 23-25Put one tick per region, name the ticks, and add a title and legend.
  9. 26tight_layout adjusts spacing so labels do not overlap.
⚠️

A truncated y axis on a bar chart exaggerates differences. If you need to zoom, use a line or dot plot instead.

Scatter plots: relationships between two variables

A scatter plot draws one dot per observation, with one variable on each axis. It answers questions such as 'do taller people weigh more?' or 'does more study time go with higher scores?'. You are looking at the overall pattern: an upward cloud means a positive relationship, a downward cloud a negative one, a shapeless blob means little relationship, and isolated points are outliers worth investigating.

ax.scatter(x, y) accepts s for dot size, c for colour and alpha for transparency. Transparency is valuable when points overlap, because dense areas become darker. You can also map a third variable to colour, which is how many exploratory plots reveal groups.

To make the data reproducible I generate it with a seeded random generator. The correlation coefficient is printed as a number because a picture and a statistic support each other: the plot shows the shape and the number summarises its strength. Remember that correlation is not causation.

python
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
hours = rng.uniform(0, 10, 60)
score = 45 + 4.5 * hours + rng.normal(0, 6, 60)
group = np.where(hours > 5, "tab:orange", "tab:blue")

r = np.corrcoef(hours, score)[0, 1]
print("correlation:", round(float(r), 3))

fig, ax = plt.subplots(figsize=(5.5, 3.8))
ax.scatter(hours, score, c=group, alpha=0.75, s=36)
slope, intercept = np.polyfit(hours, score, 1)
xs = np.array([0, 10])
ax.plot(xs, intercept + slope * xs, color="black", linewidth=1.5)
ax.set_title("Study time and test score")
ax.set_xlabel("Hours studied")
ax.set_ylabel("Score")
plt.show()
Expected output
correlation: 0.942

Line by line

  1. 4A seeded generator, so everyone sees the same dots.
  2. 5Sixty study times between 0 and 10 hours.
  3. 6Scores that rise with study time plus random noise.
  4. 7Colour dots by whether study time is above 5 hours.
  5. 9-10Compute the correlation coefficient and print it rounded.
  6. 13Draw the points with transparency and a fixed size.
  7. 14-16Fit a straight line with polyfit and draw it across the x range.
  8. 17-19Title and labels.

Histograms: the shape of your data

A histogram groups numbers into ranges called bins and draws a bar showing how many values fall in each bin. It answers 'what does this distribution look like?': is it symmetric, skewed, does it have two peaks, are there extreme values? That makes it one of the first charts to draw for any numeric column.

The number of bins matters. Too few and you lose detail; too many and you see noise. There is no perfect answer, so try several. You can pass an integer, or edges such as bins=[0, 10, 20, 30]. ax.hist returns the counts and the bin edges, which is useful because you can print exactly the numbers behind the picture.

A histogram differs from a bar chart: its x axis is a continuous scale, so the bars touch, and the order of the bars is fixed. Use density=True if you want areas to sum to 1 when comparing samples of different sizes.

python
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
heights = rng.normal(loc=165, scale=8, size=500)
print(round(float(heights.mean()), 2), round(float(heights.std()), 2))

fig, axes = plt.subplots(1, 2, figsize=(8, 3.2), sharey=True)
counts, edges, _ = axes[0].hist(heights, bins=5, color="#7a5cc7", edgecolor="white")
axes[0].set_title("5 bins")
axes[1].hist(heights, bins=25, color="#7a5cc7", edgecolor="white")
axes[1].set_title("25 bins")
for ax in axes:
    ax.set_xlabel("Height (cm)")
axes[0].set_ylabel("People")
print(counts.astype(int).tolist(), int(counts.sum()))
fig.tight_layout()
plt.show()
Expected output
163.97 7.5
[7, 99, 231, 133, 30] 500

Line by line

  1. 4-5Five hundred simulated heights around 165 cm, using a seeded generator.
  2. 6Mean and standard deviation of the sample.
  3. 8Two side-by-side Axes that share the y scale so the heights are comparable.
  4. 9Draw a 5-bin histogram; hist returns counts, edges and the bar objects.
  5. 11-12The same data with 25 bins shows a smoother shape.
  6. 13-14Loop over both Axes to set the same x label.
  7. 16Print the five counts and confirm they add up to 500.
ℹ️

Bin choice can change the story. Draw the histogram at two or three bin counts before you decide what the data 'looks like'.

Subplots, layout and styling

plt.subplots(rows, cols) returns a Figure and an array of Axes, one per cell. With a single row or column the array is one-dimensional, and with both it is two-dimensional, indexed as axes[row, col]. Use axes.flat when you just want to loop over every one of them.

Shared axes (sharex=True, sharey=True) keep scales identical across plots, which is essential when the charts are meant to be compared; different scales make two similar-looking lines mean very different things. fig.suptitle adds a title for the whole figure, and fig.tight_layout() (or layout='constrained' at creation) stops labels from colliding.

Annotations point at what matters. ax.annotate('peak', xy=(x, y), xytext=(x2, y2), arrowprops=dict(arrowstyle='->')) draws a label and an arrow, and ax.axhline or ax.axvline draws a reference line such as a target or an average. A chart that tells the reader where to look is better than one that makes them hunt.

python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)
fig, axes = plt.subplots(2, 2, figsize=(7, 5), sharex=True)
fig.suptitle("Four views of a wave")

axes[0, 0].plot(x, np.sin(x), color="tab:blue")
axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x), color="tab:green", linestyle="--")
axes[0, 1].set_title("cos")
axes[1, 0].fill_between(x, np.sin(x), alpha=0.4)
axes[1, 0].axhline(0, color="black", linewidth=0.8)
axes[1, 0].set_title("area under sin")

peak = int(np.argmax(np.sin(x)))
axes[1, 1].plot(x, np.sin(x))
axes[1, 1].annotate("peak", xy=(x[peak], 1.0), xytext=(4, 0.7),
                    arrowprops=dict(arrowstyle="->"))
axes[1, 1].set_title("annotated")

for ax in axes.flat:
    ax.grid(True, alpha=0.3)
fig.tight_layout()
print(axes.shape, round(float(x[peak]), 3))
plt.show()
Expected output
(2, 2) 1.587

Line by line

  1. 4100 evenly spaced x values from 0 to 2 pi.
  2. 5-6A 2 by 2 grid of Axes sharing the x axis, plus an overall figure title.
  3. 8-11Top row: a sine line and a dashed cosine line, indexed as axes[row, col].
  4. 12-14Bottom left: fill the area between the curve and zero and add a zero reference line.
  5. 16Find the index where the sine curve is highest.
  6. 17-20Bottom right: plot again and add an annotation with an arrow pointing at the peak.
  7. 22-23axes.flat loops over all four Axes to add light grid lines.
  8. 24-25Tidy the layout and print the grid shape and the x position of the peak.

Labels, colour and saving your chart

Good charts are readable at a glance. Use a clear title that states what is shown, label both axes with units, pick colours with enough contrast, and avoid using colour as the only way to tell series apart, because some readers cannot distinguish certain colours. Markers and line styles give a second signal. Keep the number of series small enough that the legend is not a puzzle.

When you want the chart as a file, call fig.savefig('chart.png', dpi=150) before plt.show(). The format comes from the extension: PNG for web pages, SVG or PDF for sharp vector graphics in documents. bbox_inches='tight' trims empty margins. Save from the figure, not from plt, so you are certain which chart is written.

You can also save into memory with io.BytesIO, which is how web apps send an image without touching the disk. The example below does exactly that, and checks the first bytes of the result: every PNG file begins with the same signature. It also shows plt.close(fig), which frees the memory of figures you no longer need, important in scripts that make hundreds of charts.

python
import io
import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
rain = [120, 80, 60, 95]

fig, ax = plt.subplots(figsize=(4.5, 3))
ax.bar(months, rain, color="#2a9d8f")
ax.set_title("Monthly rainfall")
ax.set_ylabel("Rainfall (mm)")

buffer = io.BytesIO()
fig.savefig(buffer, format="png", dpi=100, bbox_inches="tight")
data = buffer.getvalue()
print(data[:8] == b"\x89PNG\r\n\x1a\n", len(data) > 1000)

fig.savefig("rainfall.png", dpi=150)
plt.show()
plt.close(fig)
Expected output
True True

Line by line

  1. 4-5Four months of made-up rainfall values for the demo.
  2. 7-10A simple bar chart with a descriptive title and a y label that includes the unit.
  3. 12-13Create an in-memory file and save the figure into it as a PNG at 100 dots per inch; bbox_inches='tight' trims margins.
  4. 14Read all the bytes back out of the buffer.
  5. 15Check the 8-byte PNG signature and that the image is not empty.
  6. 17Also write a real file (in this browser it goes to a temporary virtual file system).
  7. 18-19Show the figure, then close it to release its memory.
πŸ’‘

Use dpi=150 or more for slides and print, and keep the default for quick checks. SVG stays sharp at any zoom and is a good choice for the web.

Seaborn: statistical charts in one line

Seaborn is a library built on top of Matplotlib that specialises in statistical charts. It understands DataFrames, so you name columns instead of passing arrays: sns.histplot(data=df, x='age'), sns.boxplot(data=df, x='group', y='score'), sns.scatterplot(..., hue='group'). The hue argument splits the data by colour automatically, and the default styling is more polished than raw Matplotlib.

Seaborn is not available in this in-browser environment, so the example below is shown as static code to run on your own machine after pip install seaborn (the virtual environment lesson explains how to do that safely). Because Seaborn returns ordinary Matplotlib Axes, everything you learned above still applies: you can set titles, labels and save the figure in exactly the same way.

A heatmap is a good example of Seaborn's value. It shows a grid of numbers, such as a correlation matrix, as colours, with annot=True writing each value in its cell. In plain Matplotlib you would use ax.imshow and then add the text yourself. The second block below shows how far you can get with only Matplotlib, which does run in the browser.

Seaborn version (run on your computer)run on your computer
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "hours": [1, 2, 3, 4, 5, 6, 7, 8],
    "score": [52, 55, 61, 64, 70, 74, 79, 85],
    "age":   [20, 22, 21, 25, 24, 23, 26, 27],
    "group": ["a", "a", "b", "b", "a", "b", "a", "b"],
})

sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
sns.scatterplot(data=df, x="hours", y="score", hue="group", ax=axes[0])
sns.heatmap(df[["hours", "score", "age"]].corr(), annot=True, fmt=".2f",
            cmap="viridis", ax=axes[1])
axes[1].set_title("Correlation")
plt.show()

Line by line

  1. 1-3Import pandas, seaborn (conventionally sns) and Matplotlib.
  2. 5-10A tiny table with two numeric relationships and a group label.
  3. 12Apply a clean built-in visual theme to all following charts.
  4. 13A figure with two Axes; Seaborn will draw onto them through ax=.
  5. 14Scatter plot using column names; hue colours points by group and adds a legend.
  6. 15-17A heatmap of the correlation matrix, with numbers written in each cell to 2 decimals.
  7. 18Show the figure, like any Matplotlib chart.
The same heatmap with Matplotlib only
import numpy as np
import matplotlib.pyplot as plt

labels = ["hours", "score", "age"]
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8])
score = np.array([52, 55, 61, 64, 70, 74, 79, 85])
age = np.array([20, 22, 21, 25, 24, 23, 26, 27])
corr = np.corrcoef([hours, score, age])

fig, ax = plt.subplots(figsize=(4.2, 3.6))
image = ax.imshow(corr, cmap="viridis", vmin=-1, vmax=1)
ax.set_xticks(range(3))
ax.set_yticks(range(3))
ax.set_xticklabels(labels)
ax.set_yticklabels(labels)
for i in range(3):
    for j in range(3):
        ax.text(j, i, f"{corr[i, j]:.2f}", ha="center", va="center", color="white")
fig.colorbar(image, ax=ax)
ax.set_title("Correlation")
print(round(float(corr[0, 1]), 3))
plt.show()
Expected output
0.998

Line by line

  1. 4-7Three variables and their correlation matrix; each row is a variable.
  2. 9-10imshow draws the matrix as coloured cells; fixing the colour range to -1..1 makes colours comparable.
  3. 11-14Place one tick per variable and name them.
  4. 15-17Write each coefficient in its cell, centred.
  5. 18Add a colour bar so the colours can be decoded.
  6. 20Print one coefficient as a numeric check.

Plotly and choosing the right tool

Plotly produces interactive charts: you can hover for exact values, zoom, pan and toggle series. Its plotly.express module is the quick interface: px.scatter(df, x='hours', y='score', color='group') returns a figure that you display with fig.show() or write to a standalone HTML file with fig.write_html('chart.html'). Like Seaborn, it is not part of the browser runtime on this site, so the code below is static and meant for your own computer after pip install plotly.

How do you choose? Use Matplotlib when you need full control or a static image for a paper, report or script, and for the fundamentals. Use Seaborn when you are exploring a DataFrame statistically and want good-looking defaults with little code. Use Plotly when readers will explore the chart themselves, in a web page or dashboard. They are not rivals: many projects use two of them.

Whatever the tool, the design questions are the same. What is the one message? Which chart type matches the data? Are the axes honest and labelled? Have I removed anything that is not helping? Answer those first and the library becomes a detail.

Interactive chart (run on your computer)run on your computer
import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    "hours": [1, 2, 3, 4, 5, 6, 7, 8],
    "score": [52, 55, 61, 64, 70, 74, 79, 85],
    "group": ["a", "a", "b", "b", "a", "b", "a", "b"],
})

fig = px.scatter(df, x="hours", y="score", color="group",
                 title="Study time and score")
fig.update_layout(xaxis_title="Hours studied", yaxis_title="Score")
fig.write_html("scatter.html")
fig.show()

Line by line

  1. 1-2Import pandas and Plotly Express, conventionally px.
  2. 4-8A small DataFrame with two numeric columns and a group column.
  3. 10-11One call builds an interactive scatter plot; color splits the points by group.
  4. 12Set readable axis titles.
  5. 13Save a self-contained HTML file you can open in any browser or share.
  6. 14Open the chart interactively, with hover, zoom and pan.
ℹ️

Check the current Plotly documentation before relying on an option name. The library evolves, and the core ideas above stay the same.

Common mistakes

❌ Mixing the two plotting styles

Calling plt.plot for one chart and ax.plot for another in the same script can draw onto the wrong plot, especially once you have several. Pick the object-oriented style, fig, ax = plt.subplots(), and call methods on ax throughout.

❌ Truncating the y axis on a bar chart

Bars encode value by length, so starting the axis above zero makes small gaps look dramatic. Start bar charts at zero, or switch to a line or dot chart if you need to zoom in.

❌ Forgetting labels, units and titles

A chart with unlabelled axes cannot be interpreted without the code that made it. Add a title that says what is shown and axis labels with units every time.

❌ Letting figures pile up in memory

In a script that makes many charts, each open figure stays in memory. Call plt.close(fig) after saving, and use savefig before plt.show(), because show can clear the figure afterwards.

❌ Comparing charts with different scales

Two side-by-side plots with automatic, different y ranges can look alike while showing very different values. Use sharey=True, or set the same ylim, whenever the charts are meant to be compared.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. In Matplotlib, what is an Axes?

Q2. Which chart type is best for the distribution of one numeric column?

Q3. Why should bar charts start the y axis at zero?

Q4. What does plt.subplots(2, 3) return?

Q5. Which call writes the current figure to a PNG file?

Q6. When is Plotly a better choice than Matplotlib?

Frequently asked questions

Yes, at least the basics. Seaborn draws onto Matplotlib Axes, so titles, labels, sizes, subplots and saving are all Matplotlib. A little Matplotlib knowledge makes Seaborn far less mysterious.

Call plt.show() at the end. In notebooks charts usually appear automatically, but in a plain script, nothing is displayed until show runs. If you only need a file, use fig.savefig(...) instead.

Use df.plot(x='a', y='b', kind='line') or df['col'].plot.hist(). These return a Matplotlib Axes, so you can customise them with the same methods. See the pandas lesson for the data side.

As a rule of thumb, when a legend becomes hard to match to lines, you have too many. Group minor series, highlight one or two, or split the data across subplots.

Trends over time suit lines, comparisons between categories suit bars, relationships between two numbers suit scatter plots, and distributions suit histograms. Start from the question you want answered, then pick the chart.

Key takeaways

  • βœ“A Figure is the canvas and an Axes is one plot; fig, ax = plt.subplots() is the best starting point.
  • βœ“Lines show trends, bars compare categories (from zero), scatter plots show relationships, histograms show distributions.
  • βœ“Titles, axis labels with units, legends and sensible colours make a chart readable without explanation.
  • βœ“plt.subplots(rows, cols) builds grids of plots; share axes when charts are meant to be compared.
  • βœ“Save with fig.savefig, choose PNG for the web and SVG or PDF for documents, and close figures you no longer need.
  • βœ“Seaborn adds statistical charts on top of Matplotlib, and Plotly adds interactivity; both run on your own computer.