Module 1 · Beginner · Getting started with Python charts

How to choose the right chart for your data

Which chart to use for which data: match numeric, categorical, time and place data to line, bar, scatter, histogram, box, heatmap and more charts.

By theprogrammers team · · 14 min read

The most common charting mistake isn't a wrong colour or a missing label. It's choosing the wrong type of chart: a pie chart with 15 slices, a line joining categories that have no order, a bar chart for a trend over 200 days. The data is correct, but the picture hides the answer.

The fix is simple: start from the question you want the chart to answer, not from the chart types you know. This lesson shows how to choose a chart from your question and from the type of data you have, gives you lookup tables for one, two and three or more columns, a reference of 25 common charts, Python examples of the six you'll use most, and the mistakes to avoid.

Start with the question

Almost every chart answers one of five kinds of question:

Your question is about…Example questionBest charts
Change over timeHow did monthly sales change this year?Line chart; bar chart for a few periods
Comparing categoriesWhich city has the most customers?Bar chart (horizontal for long names)
DistributionHow are exam marks spread out?Histogram, box plot
RelationshipDo students who study more score higher?Scatter plot
Part of a wholeWhat share of revenue comes from each product?Stacked bar, or a pie chart with few slices

Say your question in one sentence first. The type of question points to the chart.

Know your data types

The second thing that decides the chart is the type of data in each column you want to show. Every column is one of these:

Data typeWhat it isExamplesCan you average it?
Continuous numericAny value in a range, including decimalsHeight, price, temperature, time takenYes
Discrete numericWhole-number countsNumber of children, items in a cart, goalsYes
Nominal categoricalLabels with no orderCity, colour, payment method, brandNo: count them instead
Ordinal categoricalLabels with a natural orderSize S/M/L, rating poor/good/excellent, education levelNo, but you can order them
BinaryExactly two valuesYes/no, passed/failed, churned or notThe share of "yes"
Date and timePoints in timeOrder date, login time, monthNo: you sort and group by it
GeographicPlacesState, PIN code, latitude and longitudeNo
TextFree-form wordsReviews, comments, tweetsNo: count words or topics first

A quick test: if subtracting two values makes sense (₹500 − ₹300), it's numeric. If it doesn't ("Pune" − "Delhi"), it's categorical. Watch out for categories stored as numbers: PIN codes, roll numbers and class 1/2/3 look numeric, but averaging them means nothing, so chart them as categories.

Which chart for which type of data

Now combine them. Look up how many columns you're charting and what type each one is:

One column

DataQuestionBest chartAlso good
One continuous numberHow are values spread?HistogramBox plot, density (KDE) plot, violin plot
One discrete number with few values (0–10)How common is each value?Bar chart of counts, in numeric orderHistogram with one bin per value
One nominal categoryHow common is each category?Sorted bar chart of countsHorizontal bars for long names; pie for 2–4 categories
One ordinal categoryHow common is each level?Bar chart in the natural order (don't sort by size)Stacked 100% bar for survey answers
One binary columnWhat share is "yes"?A single number or one barPie or donut with two slices
One text columnWhat do people talk about?Bar chart of the most common words or topicsWord cloud (for impressions only)
One geographic columnHow does it vary by place?Choropleth map (regions shaded by value)Sorted bar chart of regions, which is easier to compare

Two columns

DataQuestionBest chartAlso good
Number vs numberAre they related?Scatter plotHexbin or 2D histogram for thousands of points; add a trend line
Number over date/timeHow did it change?Line chartArea chart for totals; bars for a few periods (e.g. 4 quarters)
Number by nominal categoryWhich group is bigger?Bar chart of the average or totalDot plot or lollipop chart for many categories
Number by category: spreads, not just averagesHow do the groups differ?Box plots side by sideViolin plot, strip/swarm plot, overlapping histograms for 2 groups
Number by ordinal categoryDoes it rise with the level?Bar or line in the natural orderBox plots in order
Category vs categoryHow do they combine?Heatmap of counts (a crosstab)Grouped bars, stacked 100% bars
Binary outcome by categoryWhich group says "yes" most?Bar chart of the share of "yes"Stacked 100% bar
Category over timeHow did the mix change?Stacked area or stacked bar over timeSeveral small line charts
Number by placeWhere is it highest?Choropleth mapBubble map for cities; sorted bar chart

Three or more columns

DataBest chartHow
Two numbers + a categoryScatter plot coloured by categoryhue in Seaborn, or one scatter call per group
Two numbers + a third numberBubble chart or scatter coloured with a colormapPoint size or colour shows the third number
Number over time for several groupsLine chart with one line per groupHighlight one; use small multiples beyond about 4 groups
Number by two categoriesHeatmap or grouped bar chartRows = one category, columns = the other, colour = value
Many numeric columnsCorrelation heatmap or pair plotSee every pair at once
Anything × a category with many groupsSmall multiples (facets)The same small chart repeated per group, on shared axes

The full chart reference

Here are the common charts, what each is for, and when to avoid it. Charts not covered in this module (violin, heatmap, pair plot and so on) are taught in the Seaborn and Matplotlib in depth modules.

ChartBest forData it needsAvoid when
Line chartTrends over timeDate/ordered x + numberThe x-axis has unordered categories
Area chartTotals over time, and how parts add upDate + number(s)Comparing several series that overlap
Bar / column chartComparing amounts between categoriesCategory + numberShowing a long, continuous time series
Horizontal bar chartRankings, long category namesCategory + numberCategories have a time order (use columns or a line)
Grouped bar chartComparing groups within categories2 categories + numberMore than 3–4 bars per group
Stacked bar chartA total and its parts2 categories + numberYou need to compare the middle segments precisely
100% stacked barShares of a whole across groups, survey answers2 categories + numberThe totals matter
Lollipop / dot plotMany categories, cleaner than barsCategory + numberFew categories (bars are fine)
HistogramShape of one numeric variableOne numberData is categorical (use a bar chart)
Density (KDE) plotSmooth shape; comparing 2–3 distributionsOne number (+ category)Small samples, where the smoothing invents shape
Box plotComparing spreads and outliers across groupsCategory + numberThe audience isn't familiar with them; data has two peaks
Violin plotBox plot plus the full shapeCategory + numberVery small groups
Strip / swarm plotShowing every point in each groupCategory + numberThousands of points per group
Scatter plotRelationship between two numbersTwo numbersOne variable is categorical
Bubble chartThree numbers at onceThree numbersPrecise size comparisons are needed
Hexbin / 2D histogramRelationships in huge datasetsTwo numbers, many rowsFew points
HeatmapValues across two categories; correlations2 categories (or a matrix) + numberExact values matter more than patterns (add labels)
Pair plotEvery relationship among a few numeric columns3–6 numeric columnsMany columns: it becomes unreadable
Pie / donut chartPart of a wholeCategory (2–4 values) + numberMore than 4–5 slices, or similar slice sizes
TreemapPart of a whole with many or nested partsHierarchy + numberPrecise comparisons
Waterfall chartHow a starting value becomes an end valueSteps + amountsSteps aren't additive
Funnel chartDrop-off through stagesOrdered stages + countsStages don't shrink in order
Choropleth mapValues by regionRegion + numberRegion size distracts (big empty states dominate)
Small multiplesComparing many groups without clutterAny chart × a categoryVery few groups
TableExact values that people will look upAnythingThe point is a pattern or trend

Charts for common tasks

TaskGood charts
Show a trendLine, area, column chart for a few periods
Rank itemsSorted horizontal bar, lollipop
Compare groupsBar, grouped bar, dot plot
Show a distributionHistogram, density, box, violin
Show a relationshipScatter, bubble, hexbin, correlation heatmap
Show composition (parts of a whole)Stacked bar, 100% stacked bar, pie (2–4 parts), treemap
Show change between two pointsSlope chart, dumbbell chart, grouped bar
Show a flow or processFunnel, waterfall, Sankey diagram
Show whereChoropleth map, bubble map
Show deviation from a target or averageDiverging bar chart, bar with a reference line
Find outliersBox plot, scatter plot, histogram

The six charts you'll use most

Here they are side by side, made from small example datasets:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(7)
fig, axes = plt.subplots(2, 3, figsize=(12, 7))

# 1. Line: change over time
months = np.arange(1, 13)
axes[0, 0].plot(months, [42, 40, 45, 47, 44, 46, 48, 50, 52, 75, 88, 55], marker="o")
axes[0, 0].set_title("Line: sales by month")

# 2. Bar: compare categories
cities = ["Kanpur", "Lucknow", "Pune", "Delhi"]
axes[0, 1].bar(cities, [120, 95, 140, 210])
axes[0, 1].set_title("Bar: customers by city")

# 3. Histogram: distribution of one number
marks = rng.normal(65, 12, 300)
axes[0, 2].hist(marks, bins=20)
axes[0, 2].set_title("Histogram: exam marks")

# 4. Scatter: relationship between two numbers
hours = rng.uniform(0, 10, 80)
score = 40 + 5 * hours + rng.normal(0, 6, 80)
axes[1, 0].scatter(hours, score)
axes[1, 0].set_title("Scatter: study hours vs score")

# 5. Box plot: compare distributions
groups = [rng.normal(m, 10, 100) for m in (60, 70, 65)]
axes[1, 1].boxplot(groups)
axes[1, 1].set_xticks([1, 2, 3], ["BCA", "BTech", "MCA"])
axes[1, 1].set_title("Box: marks by course")

# 6. Pie: parts of a whole (few parts only)
axes[1, 2].pie([55, 30, 15], labels=["Mobile", "Desktop", "Tablet"],
               autopct="%1.0f%%")
axes[1, 2].set_title("Pie: visits by device")

fig.tight_layout()
plt.show()
Six example charts in a grid: a line chart of sales by month rising to a peak in November; a bar chart of customers in four cities with Delhi highest; a bell-shaped histogram of exam marks; a scatter plot where score rises with study hours; box plots of marks for BCA, BTech and MCA; and a pie chart of visits split 55% mobile, 30% desktop and 15% tablet.

Don't worry about subplots yet: it just puts several charts in one figure, and has its own lesson later. Each chart type is covered in detail in the Matplotlib basics module.

Line chart: change over time

Use when the x-axis is time or another ordered sequence. The line's slope shows the trend. Several lines compare series, but more than about four becomes spaghetti.

Bar chart: compare categories

Use for comparing amounts across separate categories: cities, products, courses. Bars must start at zero, because readers compare their lengths. Sort the bars by value unless the categories have a natural order, and use horizontal bars when names are long.

Histogram: the shape of one variable

Shows how values are spread: where most of them fall, whether there's a long tail, and whether there are two peaks. It looks like a bar chart, but the x-axis is a range of numbers split into "bins", and there are no gaps between bars.

Scatter plot: relationship between two numbers

Each point is one item, with one number on each axis. It shows whether the two rise together, fall together, or aren't related, and it reveals clusters and outliers. It's the standard chart for checking a relationship before using statistics or a model.

Box plot: compare distributions

Summarises a distribution with its median, middle 50% (the box), range (the whiskers) and outliers (dots). Several box plots side by side compare groups compactly: marks by course, delivery time by city.

Pie chart: part of a whole

Shows how a total splits into parts. People judge angles poorly, so pie charts only work with 2 to 4 slices of clearly different sizes. With more categories, or when comparing similar values, a sorted bar chart is easier to read.

A quick decision guide

  1. Is the x-axis time? Use a line chart (or bars for a handful of periods).
  2. Comparing amounts across groups? Bar chart.
  3. One numeric variable, and you want its shape? Histogram (or a box plot to compare groups).
  4. Two numeric variables? Scatter plot.
  5. Parts of one total? A stacked bar, or a pie chart if there are only 2 to 4 parts.
  6. Two categorical variables? A heatmap of counts, or grouped bars.
  7. A number across two categories? A heatmap, or grouped bars.
  8. Many numeric columns at once? A correlation heatmap or pair plot.
  9. Places? A map, or a sorted bar chart when exact comparisons matter.
  10. People need exact values? A table may beat any chart.

Common mistakes

MistakeProblemBetter
Line chart for unordered categoriesThe line suggests a trend between, say, "Kanpur" and "Pune"Bar chart
Bar chart with the y-axis starting at 90Small differences look hugeStart bars at zero
Pie chart with 10 slicesImpossible to compare similar slicesSorted horizontal bar chart
3D chartsPerspective distorts sizesFlat 2D charts
Too many lines or coloursNothing stands outHighlight one or two series; grey out the rest
Two unrelated y-axes on one chartReaders infer a relationship that the scaling createsTwo separate charts

Practice

Choose a chart for each question.

  1. How has a city's daily air quality index changed over the last two years?
Show the answer

A line chart, with dates on the x-axis. With two years of daily values, a rolling average line on top makes the trend clearer.

  1. Is there a relationship between a phone's price and its customer rating?
Show the answer

A scatter plot: price on the x-axis, rating on the y-axis, one point per phone.

  1. How do delivery times compare across five cities, including the slow outliers?
Show the answer

Box plots side by side, one per city. They show medians, spread and outliers together; a bar chart of averages would hide the outliers.

  1. What share of a college's students are in each of 12 departments?
Show the answer

A sorted horizontal bar chart, showing counts or percentages. Twelve slices are too many for a pie chart.

  1. You have customers' age, income and whether they bought a product. Which chart shows how age and income relate to buying?
Show the answer

A scatter plot of age against income, with points coloured by bought / didn't buy. Two numbers plus a category is exactly the "scatter coloured by category" case.

  1. Which chart for the number of children per family (0 to 6)?
Show the answer

A bar chart of counts with the values 0 to 6 in numeric order. It's discrete numeric data with only a few values, so one bar per value is clearer than a binned histogram.

Interview questions

How does the type of data affect the choice of chart?

Numeric data can be binned and plotted on continuous axes (histograms, scatter, line charts); categorical data is counted or compared (bar charts); time data is shown in order (line charts); combinations decide the chart, for example number vs number gives a scatter plot, category vs number gives bars or box plots, and category vs category gives a heatmap or stacked bars.

How do you decide which chart to use?

Identify the question: trends over time call for line charts; comparisons between categories for bar charts; distributions for histograms or box plots; relationships between numeric variables for scatter plots; and part-to-whole for stacked bars or, with few parts, pie charts.

When should you avoid pie charts?

With more than a few categories, when slices are similar in size, or when comparing across several pies. People compare angles and areas poorly, so a sorted bar chart is usually clearer.

What is the difference between a bar chart and a histogram?

A bar chart compares separate categories, with gaps between bars and an order you choose. A histogram shows the distribution of one numeric variable split into adjacent bins, with no gaps, in numeric order.

What to learn next

  1. Make a chart yourself in your first chart in Python, step by step.
  2. Learn the parts of every chart in anatomy of a chart: figure, axes, ticks and legends.