More
Сhoose
UK Flag
  • Homepage
  • Blog
  • Step-by-Step: How to Create Your First Data Visualization in Python

Step-by-Step: How to Create Your First Data Visualization in Python

Step-by-Step: How to Create Your First Data Visualization in Python
Category:  Technology
Date:  
Author:  Shehan Udantha

Step-by-Step: How to Create Your First Data Visualization in Python

If you're working with data — whether it's experimental results, survey responses, or a dataset you scraped for a personal project — at some point you'll need to show, not just tell. A well-made chart can communicate a pattern in your data faster than a paragraph of prose ever could. This guide walks through building your first Python visualization from scratch, using nothing but pandas and matplotlib, two libraries you'll return to constantly in analysis work.

By the end, you'll have a working line chart, an understanding of why each line of code does what it does, and enough context to start customizing visualizations for your own data.

Why start with matplotlib?

There are dozens of Python visualization libraries — Seaborn, Plotly, Bokeh, Altair — and most of them are worth learning eventually. But nearly all of them are built on top of matplotlib or borrow its conventions. Learning matplotlib first means you're learning the grammar that everything else assumes you already know. It's also the library you'll see in almost every codebase, tutorial, and Stack Overflow answer, so fluency here pays off immediately.

Step 1: Set up your environment

If you haven't already, install the two libraries you'll need. Open a terminal and run:

pip install pandas matplotlib

If you're working in a Jupyter notebook (recommended for this kind of exploratory work), make sure it's installed too:

pip install notebook

A quick sanity check — run this in a Python file or notebook cell:

import pandas as pd
import matplotlib.pyplot as plt

print("Setup successful")

If that runs without errors, you're ready.

Step 2: Get your data into a DataFrame

Real-world data usually comes from a CSV, an Excel file, or an API. For this walkthrough, we'll keep things simple and construct a small dataset by hand, so you can focus entirely on the visualization logic rather than data wrangling.

data = {
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "revenue": [12000, 15500, 14200, 18700, 21300, 19800]
}
df = pd.DataFrame(data)
print(df)

This gives you a pandas DataFrame — the standard container for tabular data in the Python data ecosystem. Once your own data is in this format (via pd.read_csv(), pd.read_excel(), or similar), everything below applies just the same.

Step 3: Create a basic plot

Here's the minimum code needed to turn that DataFrame into a chart:

plt.plot(df["month"], df["revenue"])
plt.show()

Two lines. That's genuinely all it takes to go from numbers to a picture. plt.plot() draws the line, and plt.show() renders it in a window (or inline, if you're in a notebook).

It won't look like much yet — no labels, no title, default styling. That's the point of the next step.

Step 4: Add labels, a title, and basic styling

A chart without axis labels or a title is a chart nobody but you can interpret. This is the step most beginners skip and most reviewers will flag.

plt.figure(figsize=(8, 5))
plt.plot(df["month"], df["revenue"], marker="o", linewidth=2, color="#2E86AB")
plt.title("Monthly Revenue (First Half of Year)", fontsize=14, fontweight="bold")
plt.xlabel("Month")
plt.ylabel("Revenue (USD)")
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()

A few things worth understanding here, since each does a specific job:

  • plt.figure(figsize=(8, 5)) sets the canvas size in inches, before anything is drawn on it.
  • marker="o" places a visible dot at each data point, which makes it easier to see exactly where your measurements are, rather than just the interpolated line between them.
  • plt.grid(True, alpha=0.3) adds a faint background grid — useful for reading approximate values off the chart without cluttering it.
  • plt.tight_layout() automatically adjusts spacing so labels don't get clipped at the edges of the figure. It's easy to forget and its absence is a common cause of cut-off axis labels in early drafts.
Step 5: Save the figure to a file

For a report, presentation, or blog post, you'll want the chart as an image file rather than just displayed on screen.

plt.savefig("monthly_revenue.png", dpi=150)

Call savefig() before plt.show() — once show() renders the plot, matplotlib clears the figure from memory, and a savefig() call afterward may produce a blank image. The dpi (dots per inch) parameter controls resolution; 150–300 is a reasonable range for print-quality output, while 72–100 is fine for web use.

Step 6: Try a different chart type

Line charts suit continuous trends over time. Not all data is like that. If you're comparing discrete categories — say, revenue across five product lines rather than six months — a bar chart usually communicates the comparison more clearly:

plt.figure(figsize=(8, 5))
plt.bar(df["month"], df["revenue"], color="#2E86AB")
plt.title("Monthly Revenue (First Half of Year)")
plt.xlabel("Month")
plt.ylabel("Revenue (USD)")
plt.tight_layout()
plt.show()

The underlying pattern — figure, plot call, labels, layout, save — stays identical. Once you know this pattern, switching between plot(), bar(), scatter(), and hist() is mostly a matter of swapping one function call and adjusting labels to match.

A note on choosing the right chart

It's worth pausing on this before you visualize anything for a real audience. The most common mistake in early data visualization isn't a styling error — it's a mismatch between the chart type and the question being asked:

  • Line chart — a trend over a continuous variable, usually time
  • Bar chart — comparing magnitudes across discrete categories
  • Scatter plot — the relationship between two continuous variables
  • Histogram — the distribution of a single variable

Picking correctly here matters more than any amount of color customization. A beautifully styled chart that answers the wrong question is still the wrong chart.

Where to go from here

You now have a repeatable pattern: get data into a DataFrame, choose a chart type that matches your question, plot it, label it, and save it. From here, natural next steps include:

  • Seaborn, for statistical plots (distributions, correlations, categorical comparisons) with better default aesthetics and less code
  • Subplots, for placing multiple related charts in a single figure using plt.subplots()
  • Custom color palettes and themes, particularly matplotlib's built-in styles (like plt.style.use("seaborn-v0_8-whitegrid")) if you want a consistent look across a whole project or report

The gap between "a chart that technically works" and "a chart that clearly communicates" is almost entirely about labeling, appropriate chart choice, and restraint — not about mastering more advanced libraries. Get comfortable with the basics above, and most of what follows is refinement, not reinvention.