Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 31 Β· Data Preparation and Design

Time Series, Maps and Other Special Charts

Learn when and how to draw date axes, range sliders, candlesticks, choropleth maps, treemaps, sunbursts and Sankey diagrams, and prepare the data with pandas.

Bars, lines and scatter plots cover most of your charting life. A handful of other shapes cover the rest: data that unfolds over time, data attached to places, data that nests inside other data, and data that flows from one stage to the next. Each of these has its own data requirements, and nearly every "my chart looks wrong" problem with them comes from preparing the table badly, not from the plotting call.

This lesson shows what Plotly, Bokeh and Altair offer for these special charts, and then focuses on the part you can practice here: shaping the data. The plotting libraries themselves cannot run on this site, so every library call below is read-only. The runnable examples are stand-ins that use pandas in your browser to build exactly the tables those charts expect. If you have not met tidy tables yet, read Preparing Data: Tidy Format and Reshaping first.

Time series: dates are an axis, not a label

A time axis is different from a category axis. Categories are spaced evenly and unordered by default. Dates have real distances: the gap between 1 January and 8 January is seven times the gap between 1 January and 2 January, and the chart must show that. All three libraries treat a column as a time axis when it holds real date types (or ISO date strings that they can recognize).

Python
import plotly.express as px

fig = px.line(df, x="date", y="visits")
fig.update_xaxes(
    rangeslider_visible=True,
    rangeselector=dict(buttons=[
        dict(count=1, label="1m", step="month", stepmode="backward"),
        dict(count=6, label="6m", step="month", stepmode="backward"),
        dict(step="all"),
    ]),
)

Read-only. In Plotly, the range slider is a small overview strip under the chart, and the range selector is a row of buttons that jump to the last month, six months, or everything.

In Altair you declare the type with a suffix, x="date:T", and Vega-Lite picks a sensible tick format. In Bokeh you create the figure with x_axis_type="datetime". In every library the chart is only as good as the column you pass in. A column of strings like "Jan 5" becomes a category axis and silently loses the spacing.

Gaps, resolution and resampling

Real series are messy. Days are missing, some readings arrive minutes apart and others hours apart, and thousands of daily points look like noise. Three operations fix most of this:

  • Resample to a coarser step (day to week, week to month) with an aggregate: a sum for counts, a mean for rates and prices.
  • Roll a window (a 7-day mean) to smooth noise while keeping the original resolution.
  • Reindex to a regular step so that missing days become visible gaps (NaN) instead of being skipped. A line chart connects neighbouring points, so a silently missing week draws a misleading straight line across it.
Python Resample, smooth and expose gaps

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.

Notice three things in the output. The weekly buckets end on Sundays (W means "week ending Sunday"), so the first bucket holds only five days and the last only two. Those partial buckets look like a collapse in traffic, so label them, trim them, or use a mean. The rolling mean is NaN until a full window of seven values exists. And asfreq("D") turns three missing days into three explicit gaps that a charting library can draw as breaks.

flowchart LR
    A["Raw events<br/>irregular times"] --> B["Parse dates<br/>real datetime type"]
    B --> C["Resample<br/>sum or mean per step"]
    C --> D["Reindex<br/>make gaps explicit"]
    D --> E["Chart<br/>line with date axis"]

A time-series chart is the end of a short pipeline; skipping a step is where misleading lines come from.

Candlestick charts

A candlestick shows four numbers per period: open, high, low, close (OHLC). The body spans open to close, the thin "wicks" reach the high and low, and color tells you whether the period closed up or down. In Plotly it is one trace type:

Python
import plotly.graph_objects as go

fig = go.Figure(go.Candlestick(
    x=ohlc.index, open=ohlc["open"], high=ohlc["high"],
    low=ohlc["low"], close=ohlc["close"],
))
fig.update_layout(xaxis_rangeslider_visible=False)

Read-only. Plotly adds a range slider to candlesticks by default, which many people switch off.

Most raw data is a stream of individual prices, not OHLC rows. pandas builds the candles with resample(...).ohlc().

Python Turn ticks into OHLC candles

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.

You will build a full candlestick chart in Project: Stock Price Candlestick Chart.

Maps: values attached to places

There are two families of map chart, and they answer different questions.

  • Scatter geo (point maps) place a mark at a latitude and longitude. They suit events and locations: stores, earthquakes, deliveries. Size or color can carry a number. In Plotly: px.scatter_geo(df, lat="lat", lon="lon", size="sales").
  • Choropleths fill whole regions (countries, states) with a color. They suit rates and averages per region. In Plotly: px.choropleth(df, locations="iso_alpha", color="rate"), where locations holds country codes. Altair draws maps with mark_geoshape() and a GeoJSON or TopoJSON shape file; Bokeh uses patch glyphs fed with polygon coordinates.

Two rules save you from most map mistakes.

  1. Join on a stable code, not a name. Names vary ("Czechia" or "Czech Republic", "CΓ΄te d'Ivoire" or "Ivory Coast"). ISO country codes or official region identifiers do not. A failed join does not raise an error; the region just stays blank.
  2. Fill with a rate, not a raw count. A choropleth colors area, and big regions look important even if they are sparsely populated. Total sales by country mostly redraws the population map. Use sales per person, a percentage, or an index, and say so in the title.

The shapes also need a projection. Web maps usually use Mercator, which stretches regions near the poles; for a world overview of rates, an equal-area or natural-earth projection is fairer.

Ask whether you need a map at all. If the question is "which regions are highest?", a sorted bar chart is easier to read than a map, because people compare lengths far more accurately than shades of color.

Hierarchies: treemap and sunburst

A treemap nests rectangles inside rectangles: the area of each rectangle is its value, and regions contain countries which contain cities. A sunburst shows the same hierarchy as concentric rings: the center is the root, and each ring is one level deeper. Both are part-to-whole charts for a hierarchy; both are poor at precise comparison, since areas and arc lengths are harder to judge than bar lengths. Use them to show "where does the bulk of the total sit?".

Python
import plotly.express as px

fig = px.treemap(sales, path=["region", "country"], values="sales")
fig2 = px.sunburst(sales, path=["region", "country"], values="sales")

Read-only. The path list names the levels from the root outward; the library adds each parent for you.

Two data rules apply. Every child must belong to exactly one parent, and parents' values must equal the sum of their children, or the areas will not add up. Checking this takes three lines of pandas.

Flows: the Sankey diagram

A Sankey diagram draws flows between stages as bands whose width is the quantity: visitors who view a page, add to cart, then pay, or energy flowing from sources to uses. The data format is a link table (source, target, value), and the library wants nodes as numbers, not names:

Python
import plotly.graph_objects as go

fig = go.Figure(go.Sankey(
    node=dict(label=nodes),
    link=dict(source=link["source"], target=link["target"], value=link["value"]),
))

Read-only. The source and target lists hold positions in the label list.

The stand-in below prepares both the hierarchy and the link table. This is the part of the work that decides whether the chart is correct.

Python Prepare treemap and Sankey data

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 last line is the useful check. For any middle node, the flow in must equal the flow out; if it does not, some visitors vanished from your data and the bands will not line up.

What is real and what is the stand-in

  • Real, but read-only: every px.*, go.* and alt.* call on this page. They need a Python environment with the libraries installed and a browser to display the result.
  • Stand-in: the pandas code in the TryIts. It is real pandas running in your browser, and it produces the same tables the charts consume, but it draws nothing.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why should you reindex a daily series to a regular frequency before plotting a line?

    A line chart joins neighbouring points. If days are missing, the line draws a straight segment across the hole. Reindexing makes the gap explicit (NaN) so the chart can break the line.
  2. 2. What do the four values of a candlestick represent for one period?

    A candle shows open, high, low and close (OHLC). The box plot uses the quartile summary instead.
  3. 3. A choropleth of total sales per country mostly looks like a population map. What is the usual fix?

    Choropleths color area, so raw counts follow the size of the region or its population. A rate or an index makes regions comparable.
  4. 4. In a Sankey link table, what do the source and target columns hold when passed to Plotly?

    Plotly's Sankey wants integer positions into the label list, so you map names to indexes before building the link dict.

Summary

  • A date axis has real spacing; pass real date types, not strings like "Jan 5".
  • Resample for a coarser step, roll for smoothing, and reindex so gaps stay visible. Watch for partial first and last buckets.
  • Candlesticks need OHLC columns; resample(...).ohlc() builds them from raw prices.
  • Join map data on stable codes, and color choropleths by rates, not counts.
  • Treemaps and sunbursts need a strict hierarchy whose parents equal the sum of children; Sankey diagrams need a source/target/value link table with node positions.
  • The plotting calls are read-only here; the pandas stand-ins prepare the same tables for real.

Next: Color, Labels and Accessibility.