Time Series and Date Axes in Python
How to plot date and time in python.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.
Time Series using Axes of type date¶
Time series can be represented using either plotly.express functions (px.line, px.scatter, px.bar etc) or plotly.graph_objects charts objects (go.Scatter, go.Bar etc). For more examples of such charts, see the documentation of line and scatter plots or bar charts.
For financial applications, Plotly can also be used to create Candlestick charts and OHLC charts, which default to date axes.
Plotly auto-sets the axis type to a date format when the corresponding data are either ISO-formatted date strings or if they're a date pandas column or datetime NumPy array.
# Using plotly.express
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")
fig.show()
# Using graph_objects
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
fig = go.Figure([go.Scatter(x=df['Date'], y=df['AAPL.High'])])
fig.show()
Time Series in Dash¶
Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.
Get started with the official Dash docs and learn how to effortlessly style & publish apps like this with Dash Enterprise or Plotly Cloud.
Sign up for Dash Club ā Free cheat sheets plus updates from Chris Parmer and Adam Schroeder delivered to your inbox every two months. Includes tips and tricks, community apps, and deep dives into the Dash architecture. Join now.
Different Chart Types on Date Axes¶
Any kind of cartesian chart can be placed on date axes, for example this bar chart of relative stock ticker values.
import plotly.express as px
df = px.data.stocks(indexed=True)-1
fig = px.bar(df, x=df.index, y="GOOG")
fig.show()
Or this facetted area plot:
import plotly.express as px
df = px.data.stocks(indexed=True)-1
fig = px.area(df, facet_col="company", facet_col_wrap=2)
fig.show()
Configuring Tick Labels¶
By default, the tick labels (and optional ticks) are associated with a specific grid-line, and represent an instant in time, for example, "00:00 on February 1, 2018". Tick labels can be formatted using the tickformat attribute (which accepts the d3 time-format formatting strings) to display only the month and year, but they still represent an instant by default, so in the figure below, the text of the label "Feb 2018" spans part of the month of January and part of the month of February. The dtick attribute controls the spacing between gridlines, and the "M1" setting means "1 month". This attribute also accepts a number of milliseconds, which can be scaled up to days by multiplying by 24*60*60*1000.
Date axis tick labels have the special property that any portion after the first instance of '\n' in tickformat will appear on a second line only once per unique value, as with the year numbers in the example below. To have the year number appear on every tick label, '<br>' should be used instead of '\n'.
Note that by default, the formatting of values of X and Y values in the hover label matches that of the tick labels of the corresponding axes, so when customizing the tick labels to something broad like "month", it's usually necessary to customize the hover label to something narrower like the actual date, as below.
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x="date", y=df.columns,
hover_data={"date": "|%B %d, %Y"},
title='custom tick labels')
fig.update_xaxes(
dtick="M1",
tickformat="%b\n%Y")
fig.show()
Moving Tick Labels to the Middle of the Period¶
new in 4.10
By setting the ticklabelmode attribute to "period" (the default is "instant") we can move the tick labels to the middle of the period they represent. The gridlines remain at the beginning of each month (thanks to dtick="M1") but the labels now span the month they refer to.
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x="date", y=df.columns,
hover_data={"date": "|%B %d, %Y"},
title='custom tick labels with ticklabelmode="period"')
fig.update_xaxes(
dtick="M1",
tickformat="%b\n%Y",
ticklabelmode="period")
fig.show()
Adding Minor Ticks¶
new in 5.8
You can add minor ticks to an axis with minor. This takes a dict of properties to apply to minor ticks. See the figure reference for full details on the accepted keys in this dict.
In this example, we've added minor ticks to the inside of the x-axis and turned on minor grid lines.
import pandas as pd
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y="GOOG")
fig.update_xaxes(minor=dict(ticks="inside", showgrid=True))
fig.show()