Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 57 ยท Projects

Project: Analysing Used Car Prices

Chart the drivers of used-car prices with Matplotlib: histograms, scatter plots with trend lines, box plots by brand, grouped bars, a depreciation fit and a polished summary figure.

Which charts would convince a buyer that a five-year-old hybrid is fairly priced? What would show a dealer which brands lose value fastest? In this project you answer those questions with pictures. You start from a clean table of used-car listings and build a chart for each question: the distribution of prices, the effect of age and mileage, the difference between brands and fuels, and a fitted depreciation curve. Then you combine them into one polished figure.

The table is synthetic: 400 listings that we generate with a fixed random seed, so everyone sees identical results, and no real cars or sellers are involved. It is already clean (the pandas course has a companion project that starts from the messy raw file and does the cleaning and the numeric analysis). Here the focus is on choosing the right chart, labelling it and keeping a consistent look.

You will use histograms, scatter plots with a colour dimension, trend lines, box plots, grouped bars, annotations and a multi-panel figure. Skills from Scatter Plots, Histograms, Box and Violin Plots and Designing Clear Charts all appear.

flowchart LR
    A["1. Distribution<br/>histogram"] --> B["2. Age<br/>scatter + trend"]
    B --> C["3. Groups<br/>box plot, grouped bars"]
    C --> D["4. Mileage<br/>colour as 3rd variable"]
    D --> E["5. Depreciation<br/>fit and residuals"]
    E --> F["6. Summary figure"]

One question per chart: pick the chart type that answers it.

Step 1: What does a typical price look like?

Start with the single most important variable, the price. A histogram shows the shape (how many cars in each price range). Mark the median and the mean with vertical lines: when they differ, the distribution is skewed, which is common for prices. A bar chart of how many listings each brand has tells us how much to trust the later brand comparisons.

Python Step 1: price histogram and listings per brand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The histogram has a long right tail (a few expensive cars, mostly young BMWs), so the mean sits to the right of the median. For a "typical" price the median is more honest. Also note that BMW has the fewest listings, so statements about BMW rest on fewer cars and are less certain.

Step 2: Price against age

The relationship that matters most is between age and price. A scatter plot shows every car. Add the median price for each age as a line over the cloud, which summarises the trend without hiding the spread. Colour the points by fuel type so a third variable is visible without a third axis.

Python Step 2: age against price, coloured by fuel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the vertical order of the colours at any age: electric cars sit highest, then hybrids, then diesel and petrol. The cloud also fans out at young ages (new BMWs and economy cars differ a lot) and tightens as the cars get old and all converge to low prices. Colour adds the fuel dimension, but it also adds overplotting; alpha=0.6 lets overlapping points show through.

Step 3: Comparing brands and fuels

Comparing groups calls for a box plot: the box shows the middle half of prices, the line the median, the whiskers the usual range, and dots the unusual cars. Sort the boxes by their median, so that the ranking is visible at a glance. A second chart shows the median price per brand and fuel type as grouped bars.

Python Step 3: box plot by brand and grouped bars by fuel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The box plot ranks the brands: BMW is clearly above the rest, and the four mass-market brands overlap heavily, so small differences between them should not be over-interpreted. The grouped bars add a second factor, and they raise a warning: some brand and fuel combinations have only a handful of cars, so their medians are fragile. Always check the counts before reading a bar (pivot_table(..., aggfunc="count") gives them).

Step 4: A third variable as colour

Mileage and age are related (older cars have driven more), so how does mileage matter on its own? A scatter plot of mileage against price, with the colour showing age, lets you see whether cars with the same mileage cost more when they are younger. c= maps a number to colour through a colormap, and fig.colorbar provides the key (see Colormaps).

Python Step 4: mileage against price, coloured by age

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The cloud slopes downwards, but the colours stack in bands: for the same mileage a younger (yellow) car costs more, and old cars (dark) cluster at high mileage and low price. In other words, age and mileage are tangled together, the same warning that the correlation table gives (age and mileage correlate at about 0.85). A chart with colour is a good way to show a confounder without any statistics.

Step 5: Fitting the depreciation curve

On a normal axis the price curve bends. If prices fall by a constant percentage per year, then the logarithm of the price falls on a straight line, which we can fit with np.polyfit(age, np.log(price), 1). The slope gives the yearly loss, and the fitted curve can be drawn back on the original axis. A residual plot (data minus fit) tells us whether the line is a good description.

Python Step 5: a fitted depreciation curve and its residuals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The red curve follows the grey cloud well. The residuals should look like a patternless band around zero: here they spread out around the line, which is expected, because brand and fuel (which the fit ignores) shift prices up and down. Strong curvature or a trend in the residuals would mean the straight-line-on-log model is wrong. This one-variable fit is a description, not a prediction: the pandas project adds brand, fuel and mileage to a regression.

Step 6: One polished summary figure

Finally, pull the best charts into one figure for a report. Choose a consistent palette (the same colour always means the same fuel), keep fonts and line widths uniform, give every panel a title that states the finding, and add a figure title. layout="constrained" handles the spacing, and savefig writes the file.

Python Step 6: a four-panel summary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the titles: each states a finding, not just the variable names ("BMW commands a premium" rather than "Price by brand"). That habit turns a set of charts into an argument, and it is the quickest way to find out whether a chart really supports the claim: if you cannot write a finding as a title, the chart is probably not needed.

Extension ideas

  • Replace the box plot with a violin plot and compare which one tells the story better for the small BMW group.
  • Add a hexbin plot of age and price (ax.hexbin) to deal with overplotting, and compare it with the scatter plot.
  • Draw one depreciation curve per brand on the same axes with np.polyfit and a loop, and label the lines directly instead of using a legend.
  • Make a small-multiples figure: one scatter panel per fuel type with sharex=True, sharey=True.
  • Show the uncertainty of the median at each age with a shaded band between the 25th and 75th percentile (ax.fill_between).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the price histogram the mean is higher than the median. What does it tell you?

    A mean to the right of the median is the usual sign of a right-skewed distribution, here a handful of expensive cars.
  2. 2. Why show the median price per age as a line over the scatter plot?

    The line gives the typical value at each age, and the points show how much cars vary around it. Both together are more honest than either alone.
  3. 3. What does c=cars['age'] with cmap='viridis_r' do in ax.scatter?

    c takes one number per point, and the colormap converts it to a colour. A colorbar explains the mapping.
  4. 4. Why is np.polyfit applied to the logarithm of the price?

    If price = A * exp(slope * age), then log(price) = log(A) + slope * age, a straight line that a degree-1 polyfit can find.
  5. 5. What should the residuals of a good fit look like?

    Residuals with no visible trend or curvature suggest the model captures the main pattern. Curvature or a drift points to a missing effect.

Summary

  • Choose the chart by the question: histogram for a distribution, scatter for a relationship, box plot for groups, grouped bars for two factors.
  • Add a trend line (here the median per age) over a scatter plot, and use colour for a third variable with a colorbar.
  • Show how many cars stand behind each box or bar; small groups deserve less trust.
  • Fit a curve (np.polyfit on log price), draw it back on the original axes and inspect the residuals.
  • Use one palette for the whole figure, write a finding as each panel's title, and save with savefig.
  • This data is synthetic: say so in the figure, and keep charts honest about what they do and do not show.

Next: Exercises lets you practise everything in this course.