文章目录
九、具有自定义日期范围的时间序列图
可以使用datetime.datetime对象或日期字符串手动设置数据范围。
9.1 使用plotly.express
# Using plotly.express
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('F:/finance-charts-apple.csv')
fig = px.line(df, x='Date', y='AAPL.High', range_x=['2016-07-01','2016-12-31'])
fig.show()
9.2 使用graph_objects
# Using graph_objects
import plotly.graph_objects as go
import datetime
x = [datetime.datetime(year=2013, month=10, day=4),
datetime.datetime(year=2013, month=11, day=5),
datetime.datetime(year=2013, month=12, day=6)]
fig = go.Figure(data=[go.Scatter(x=x, y=[1, 3, 6])])
# 使用datetime对象设置xaxis范围
fig.update_layout(xaxis_range=[datetime.datetime(2013, 10, 17),
datetime.datetime(2013, 11, 20)])
fig.show()
9.3 手动设置日期范围
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = px.line(df, x='Date', y='AAPL.High')
# 使用日期字符串设置xaxis范围
fig.update_layout(xaxis_range=['2016-07-01','2016-12-31'],
title_text="手动设置日期范围")
fig.show()
十、带范围滑块的时间序列
范围滑块是绘图下方的类似子图的小区域,允许用户在保持图表概览的同时平移和缩放 X 轴。查看更多选项的参考:https 😕/plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangeslider
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = px.line(df, x='Date', y='AAPL.High', title='带范围滑块的时间序列')
fig.update_xaxes(rangeslider_visible=True)
fig.show()
十一、带范围选择器按钮的时间序列
范围选择器按钮是与时间序列和范围滑块配合使用的特殊控件,允许用户轻松设置 x 轴的范围。查看更多选项的参考:https 😕/plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangeselector
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = px.line(df, x='Date', y='AAPL.High', title='带有范围滑块和选择器的时间序列')
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
fig.show()
十二、按缩放级别自定义刻度标签格式
该tickformatstops属性可用于根据缩放级别自定义刻度标签的格式。尝试放大下面的图表,看看刻度标签格式如何变化。查看更多选项的参考:https 😕/plotly.com/python/reference/layout/xaxis/#layout-xaxis-tickformatstops
import plotly.graph_objects as go
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = go.Figure(go.Scatter(
x = df['Date'],
y = df['mavg']
))
fig.update_xaxes(
rangeslider_visible=True,
tickformatstops = [
dict(dtickrange=[None, 1000], value="%H:%M:%S.%L ms"),
dict(dtickrange=[1000, 60000], value="%H:%M:%S s"),
dict(dtickrange=[60000, 3600000], value="%H:%M m"),
dict(dtickrange=[3600000, 86400000], value="%H:%M h"),
dict(dtickrange=[86400000, 604800000], value="%e. %b d"),
dict(dtickrange=[604800000, "M1"], value="%e. %b w"),
dict(dtickrange=["M1", "M12"], value="%b '%y M"),
dict(dtickrange=["M12", None], value="%Y Y")
]
)
fig.show()
十三、隐藏周末和假期
rangebreaks类型的 x 轴和 y 轴上可用的属性可date用于隐藏某些时间段。在下面的示例中,我们显示了两个图:一个在默认模式下显示数据中的空白,另一个在我们隐藏周末和节假日的情况下显示不间断的交易历史。请注意 12 月 21 日和 1 月 4 日的网格线之间的较小间隙,其中假期被删除。查看更多选项的参考:https 😕/plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangebreaks
注意:此功能的一个已知限制是它不支持scattergl跟踪。px.scatter在具有或px.line或或的数百个数据点的绘图上使用此功能时px.area,您可能需要传入render_mode="svg"以确保基础跟踪类型是scatter和不是scattergl。
13.1 隐藏正常周末
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = px.scatter(df, x='Date', y='AAPL.High', range_x=['2015-12-01', '2016-01-15'],
title="Default Display with Gaps")
fig.show()
13.2 隐藏周末和指定日期
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
# 'https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv'
df = pd.read_csv('f:/finance-charts-apple.csv')
fig = px.scatter(df, x='Date', y='AAPL.High', range_x=['2015-12-01', '2016-01-15'],
title="用rangebreaks来隐藏周末和假日的间隙")
fig.update_xaxes(
rangebreaks=[
dict(bounds=["sat", "mon"]), # 隐藏周末
dict(values=["2015-12-25", "2016-01-01"]) # 隐藏圣诞节和新年
]
)
fig.show()
13.3 隐藏非营业时间
上述rangebreaks功能也适用于隐藏小时时段。
import plotly.express as px
import pandas as pd
import numpy as np
np.random.seed(1)
work_week_40h = pd.date_range(start='2020-03-01', end='2020-03-07', freq="BH")
df = pd.DataFrame(dict(
date = work_week_40h,
value = np.cumsum(np.random.rand(40)-0.5)
))
fig = px.scatter(df, x="date", y="value",
title="带间隙的默认显示")
fig.show()
13.4 上午9点至下午5点以外的时间隐藏
import plotly.express as px
import pandas as pd
import numpy as np
np.random.seed(1)
work_week_40h = pd.date_range(start='2020-03-01', end='2020-03-07', freq="BH")
df = pd.DataFrame(dict(
date = work_week_40h,
value = np.cumsum(np.random.rand(40)-0.5)
))
fig = px.scatter(df, x="date", y="value",
title="用休息时间隐藏非工作时间间隔")
fig.update_xaxes(
rangebreaks=[
dict(bounds=[17, 9], pattern="hour"), # 上午9点至下午5点以外的时间隐藏
]
)
fig.show()
十四、Dash中的应用
import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div([
dcc.Graph(figure=fig)
])
app.run_server(debug=True, use_reloader=False) # Turn off reloader if inside Jupyter