TExcelTAD
Home › pandas › Pandas Plotting

Pandas Plotting

pandas can draw charts straight from a DataFrame or Series with the plot() method. Under the hood it uses Matplotlib, Python's standard plotting library, so you import matplotlib.pyplot as plt and call plt.show() to display the figure. On this site the chart appears under the text output.

A line chart

df.plot() with no arguments draws one line per numeric column, using the index as the x-axis:

python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

energy = pd.DataFrame({
    "solar_kwh": [3.1, 4.5, 6.8, 8.2, 9.0, 9.6, 9.3, 8.1, 6.4, 4.6, 3.2, 2.7],
    "grid_kwh":  [9.8, 8.9, 7.1, 5.6, 4.9, 4.2, 4.5, 5.3, 6.6, 8.0, 9.4, 10.1],
}, index=["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])

energy.plot(title="Average daily household energy", ylabel="kWh")
plt.show()
print("Plotted", len(energy), "months of", list(energy.columns))
Plotted 12 months of ['solar_kwh', 'grid_kwh']

The print at the end is just for the text output; the figure is what matters. Arguments like title=, xlabel=, ylabel=, figsize=(w, h) and grid=True customise the chart.

Chart kinds

Choose the chart type with kind= (or the matching shortcut method such as df.plot.bar()):

kind Chart Good for
"line" (default) line trends over time
"bar" / "barh" vertical / horizontal bars comparing categories
"hist" histogram the distribution of one variable
"box" box plot distribution, median and outliers
"scatter" scatter plot relationship between two columns
"pie" pie chart parts of a whole (use sparingly)
"area" stacked area cumulative totals over time

Bar charts

python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

library = pd.DataFrame({
    "loans": [412, 287, 356, 198, 240],
    "returns": [398, 301, 340, 205, 233],
}, index=["Fiction", "History", "Science", "Poetry", "Travel"])

library.plot(kind="bar", rot=0, title="Library loans by genre")
plt.show()
print("Busiest genre:", library["loans"].idxmax())
Busiest genre: Fiction

rot=0 keeps the category labels horizontal. With two columns, pandas draws grouped bars side by side.

Scatter plots

A scatter plot shows one dot per row, which is the visual counterpart of the correlation from the previous lesson. You must name the x and y columns:

python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

flats = pd.DataFrame({
    "size_m2": [38, 52, 45, 70, 85, 60, 95, 41, 77, 66],
    "rent":    [720, 910, 800, 1190, 1400, 1020, 1580, 760, 1260, 1110],
})
flats.plot(kind="scatter", x="size_m2", y="rent", title="Rent vs flat size")
plt.show()
print("correlation:", round(flats["size_m2"].corr(flats["rent"]), 3))
correlation: 0.999

The dots form an almost straight rising line, matching the correlation close to 1.

Histograms

A histogram splits values into ranges ("bins") and counts how many fall in each. Here we generate 500 seeded random reaction times so the chart is the same every run:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
reaction = pd.Series(rng.normal(loc=250, scale=30, size=500), name="ms")

reaction.plot(kind="hist", bins=20, edgecolor="white",
              title="Reaction times (ms)")
plt.show()
print(f"mean={reaction.mean():.1f} ms, std={reaction.std():.1f} ms")
mean=249.6 ms, std=28.8 ms

The bell shape is typical of normally distributed data.

Several plots in one figure

plot() returns a Matplotlib Axes object. Create a grid of axes with plt.subplots() and pass each one with ax=:

python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

week = pd.DataFrame({
    "steps": [6200, 8100, 7400, 10200, 9100, 12800, 4300],
    "sleep_h": [7.2, 6.8, 7.5, 6.1, 7.0, 8.4, 9.1],
}, index=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])

fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
week["steps"].plot(kind="bar", ax=axes[0], rot=0, color="tab:green", title="Steps")
week["sleep_h"].plot(ax=axes[1], marker="o", title="Sleep (hours)")
fig.tight_layout()
plt.show()
print("Two charts drawn side by side")
Two charts drawn side by side

Tip: For anything beyond quick looks, the Matplotlib Axes returned by plot() lets you adjust every detail: ax.set_ylim(0, 100), ax.axhline(...), ax.legend(...) and so on.

Test yourself

Which argument makes df.plot() draw a bar chart?

  1. type="bar"
  2. kind="bar"
  3. chart="bar"
  4. style="bar"

What does df.plot() use for the x-axis by default?

  1. The first column
  2. The index
  3. Row numbers only
  4. Nothing; x is required

Which chart best shows how the values of a single column are distributed?

  1. Scatter plot
  2. Pie chart
  3. Histogram
  4. Line chart