Python Data Visualization: Matplotlib, Seaborn and Plotly With pandas, Chart Choice and Clean Design
Learn to make charts in Python: install matplotlib, seaborn and plotly, line, bar, scatter and histogram examples with pandas data, choosing the right chart, labelling, colours, saving images and common mistakes.
A good chart explains data in seconds. Python offers powerful libraries to build them, and the three most popular are matplotlib (the foundation), seaborn (statistical charts with good defaults) and plotly (interactive charts). This guide walks through each with runnable examples and rules for choosing and designing charts.
Setup
pip install pandas matplotlib seaborn plotly
If you are new to Python, first read Python basics.
A sample dataset
import pandas as pd
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"sales": [120, 135, 128, 160, 175, 190],
"cost": [90, 100, 98, 115, 125, 130],
})
df["profit"] = df["sales"] - df["cost"]
pandas DataFrames hold tabular data. Load your own with pd.read_csv("file.csv").
Line chart with matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(df["month"], df["sales"], marker="o", label="Sales")
ax.plot(df["month"], df["cost"], marker="s", label="Cost")
ax.set_title("Sales vs cost, Jan to Jun")
ax.set_xlabel("Month")
ax.set_ylabel("Amount (in thousands of rupees)")
ax.legend()
ax.grid(alpha=0.3)
fig.tight_layout()
fig.savefig("sales.png", dpi=150)
plt.show()
Line charts suit trends over time. Always label axes and units, and use savefig to export a high-resolution image for reports.
Bar chart
ax = df.plot.bar(x="month", y="profit", legend=False, color="#2a7de1")
ax.set_title("Monthly profit")
ax.set_ylabel("Profit")
plt.tight_layout()
plt.show()
Use bars to compare categories. Start the vertical axis at zero for bar charts, or the differences look larger than they are.
Scatter plot and histogram
import numpy as np
rng = np.random.default_rng(1)
x = rng.normal(50, 10, 200)
y = x * 0.8 + rng.normal(0, 8, 200)
plt.scatter(x, y, alpha=0.6)
plt.xlabel("Study hours")
plt.ylabel("Score")
plt.show()
plt.hist(x, bins=15, edgecolor="white")
plt.title("Distribution")
plt.show()
Scatter plots show relationships between two numeric variables. Histograms show how values are distributed.
Seaborn for statistics
import seaborn as sns
tips = sns.load_dataset("tips")
sns.set_theme(style="whitegrid")
sns.boxplot(data=tips, x="day", y="total_bill")
plt.show()
sns.heatmap(tips[["total_bill", "tip", "size"]].corr(), annot=True, cmap="Blues")
plt.show()
Seaborn builds on matplotlib and makes box plots, violin plots, regression lines and heatmaps with a single line.
Interactive charts with plotly
import plotly.express as px
fig = px.line(df, x="month", y=["sales", "cost"], markers=True,
title="Sales vs cost")
fig.show()
fig.write_html("sales.html")
Plotly produces hover tooltips and zoom, and the HTML file can be shared or embedded on a web page. See also Flask for serving dashboards.
Choosing the right chart
- Trend over time: line chart.
- Compare categories: bar chart, horizontal if labels are long.
- Parts of a whole: stacked bar or a pie with very few slices.
- Distribution: histogram or box plot.
- Relationship: scatter plot.
- Correlations across many variables: heatmap.
Design rules that matter
- Give each chart one message, and put it in the title.
- Use colour sparingly. Highlight one series and grey the rest.
- Avoid 3D effects and truncated axes that distort.
- Make text readable at the size it will be seen.
- Choose colour-blind-safe palettes, and do not rely on colour alone.
- Cite the data source and date.
Mistakes to avoid
- Too many lines or categories in one chart.
- Missing units or labels.
- Dual axes that mislead.
- Forgetting
plt.show()in scripts or notebooks. - Plotting unsorted categories, making patterns hard to see.
For getting data to plot, read web scraping with Python and SQL basics. Excel users can compare approaches in advanced Excel formulas.
Telling a story with your charts
Before plotting, write one sentence describing what you want the reader to learn, such as 'Profit grew every month while costs stayed flat.' Use that sentence as the title, pick the chart that shows it most plainly, and remove anything that does not support it: heavy gridlines, borders and decorative colours. Annotate the key point directly on the chart using ax.annotate so readers do not hunt for it. Check the chart at the size it will be displayed, for example in a slide or a phone-sized blog column. Ask a colleague to explain what they see in five seconds. If they cannot, simplify. Save both PNG for documents and SVG for scalable web use, and keep the script so the chart can be regenerated when the data changes.
Working with Indian data
Many datasets use lakhs and crores. Format axis labels with a custom formatter so that 1500000 shows as 15 L, and label currency as rupees. Use the government's open data portal, RBI statistics and NSE or BSE downloads as practice sources, and always check the licence. Clean missing values and duplicate rows with pandas before charting, and keep a record of what you changed.
From notebook to report
Most analysts explore data in Jupyter notebooks and then export the final charts. Keep exploration and presentation separate: in the notebook, make many quick plots to understand the data, and in a clean script produce the five or six figures that go into a report. Use a shared style function that sets fonts, sizes and colours once so every chart looks consistent. Add the data source and date in a small note beneath each chart. If your audience uses Excel or PowerPoint, export PNG images at 150 to 300 dpi and paste them in, or write the figures into a spreadsheet using pandas so readers can inspect the numbers. For dashboards that update automatically, plotly Dash or Streamlit turn your scripts into web apps with little extra code, and they pair well with the Flask approach for custom projects.
Frequently asked questions
Which library should I learn first?
Start with matplotlib basics, then seaborn for faster statistical charts.
How do I save a chart as an image?
Use fig.savefig("name.png", dpi=150).
Can I make interactive charts in Python?
Yes, plotly and bokeh create interactive charts.
Why does my chart not show?
You may have forgotten plt.show() or are running in an environment without a display.
What is pandas used for?
Loading, cleaning and analysing tabular data.
Which chart is best for trends?
A line chart.
Last reviewed 8 November 2026. Rates, limits and rules change, so confirm figures with the official source before you act.
Free tools related to this article
Keep reading
Information on AMTools is for general guidance and is not professional financial, tax, legal or medical advice. Rules, rates and limits change, so check the latest official source before acting.