import plotly.io as pio
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np
# 设置plotly默认主题
pio.templates.default = 'plotly_white'
# 设置pandas打印时显示所有列
pd.set_option('display.max_columns', None)
update_xaxes / update_yaxes 常用参数介绍及示例
二者参数大同小异,因此以x轴作为示例说明。
官方示例:https://plotly.com/python/axes/
详细参数见:
https://plotly.com/python/reference/layout/xaxis/https://plotly.com/python-api-reference/generated/plotly.graph_objects.layout.html?highlight=layout%20xaxis#plotly.graph_objects.layout.XAxishttps://plotly.com/python/reference/layout/yaxis/https://plotly.com/python-api-reference/generated/plotly.graph_objects.layout.html?highlight=yaxis#plotly.graph_objects.layout.YAxistype:设置坐标轴的类型。默认情况下,plotly会根据输入数据自动调整合适的类型。
字符串枚举类型,可取 '-'、'linear'、'log、'date'、'category'、'multicategory' visible:是否显示坐标轴,默认为 True,当设置为 False 时隐藏坐标轴,但是依旧可以进行拖拽。side:设置x轴(y轴)位于绘画区域的 底部(左侧)还是 顶部(右侧)
字符串枚举类型,可取 'top'、 'bottom'、 'left'、 'right'。注:x轴只可取 'top' 或 'bottom',同样,y轴只可取 'left' 或 'right' zeroline:是否绘制零刻度线,如果为True,零刻度线将会在网格线最顶层绘制。zerolinecolor:零刻度线的颜色。
十六进制字符串,如 #ff0000rgb/rgba 字符串,如 rgb(255,0,0)hsl/hsla 字符串,如 hsl(0,100%,50%)hsv/hsva 字符串,如 hsv(0,100%,100%)CSS 颜色字符串,如 darkblue、lightyellow 等 zerolinewidth:零刻度线的宽度。整数或浮点数(像素)。showgrid:是否显示垂直于该坐标轴的网格线。默认为 Truegridcolor:垂直于该坐标轴的网格线的颜色。gridwidth:垂直于该坐标轴的网格线的宽度。[0, inf] 之间的整数或浮点数showline:是否显示坐标轴线。默认为 Falselinecolor:坐标轴线的颜色。linewidth:坐标轴线的宽度。[0, inf] 之间的整数或浮点数title:设置坐标轴标题,字典类型,包含如下属性:
font:设置坐标轴标题的字体,字典类型,包含如下属性:
color:字体颜色family:字体类型。字符串,可以为 Arial、Balto、Courier New、Droid Sans、Droid Serif、Droid Sans Mono、Gravitas One、Old Standard TT、Open Sans、Overpass、PT Sans Narrow、Raleway、Times New Romansize:字体大小。大于等于1的整数。 text:设置标题内容,字符串类型。standoff:设置坐标轴标题与刻度标签之间的距离。注意,轴标题总是被限制在绘画框内,因此实际的间距总是小于设定值或者默认值。但是可以将 automargin 设置为 True,此时 plotly.js 将会根据给定的 standoff 值自动调整边距。大于等于 0 的整数 automargin:是否让图边距适应标签长度(因为标签总是限制在边框内,此参数可以让边框自动适应标签的长度)。默认为 False
df = px.data.iris()
print(df.head())
fig = px.scatter(
df, x='sepal_length', y='sepal_width',
color='species_id', size='petal_length',
)
fig.update_xaxes(
type='linear',
side='top',
showgrid=False,
title={'font': {'size': 18}, 'text': 'Sepal Length', 'standoff': 10},
automargin=True,
)
fig.update_yaxes(
showline=True,
linecolor='black',
linewidth=3,
gridwidth=2,
title={'font': {'size': 18}, 'text': 'Sepal Width', 'standoff': 10},
automargin=True,
)
fig.write_image('../pic/axes_1.png', scale=10)
fig.show()
showticklabels:是否显示刻度标签,默认为 Trueshowtickprefix:如果为 'all',则所有的刻度标签都显示前缀;如果为 'first',则只有第一个刻度标签显示前缀;如果为 'last',则只有最后一个刻度标签显示前缀;如果为 None,则所有标签都不显示前缀。
字符串枚举型,可取 'all'(默认值)、'first'、'last'、None showticksuffix:与 showtickprefix 一样,只是将前缀改为后缀。默认值为 'all'tickprefix:设置刻度标签的前缀,字符串类型,默认为 空字符串 ""ticksuffix:设置刻度标签的后缀,字符串类型,默认为 空字符串 ""ticks:如果为空字符串 "",则不绘制刻度线,默认值;如果为 'outside',则绘制刻度线,且方向向图表外侧;如果为 'inside',则绘制刻度线,且方向向图表内侧。
字符串枚举类型,可取 ""(默认值)、'outside'、'inside' tickwidth:设置刻度线的宽度,大于等于0的整数,默认值为1ticklen:设置刻度线的长度,大于等于0的整数,默认值为5tickcolor:设置刻度线的颜色。tickmode:设置刻度的模式。如果为 'auto',则根据 nticks 调整显示的刻度数;如果为 'linear',则刻度由起始位置 tick0,和步长 dtick 决定(如果 tick0 和 dtick 都指定了,那么 tickmode的默认值变为 'linear');如果为 'array',则刻度由 tickvals 和 ticktext 指定(如果 tickvals 指定了,那么 tickmode的默认值变为 'array')nticks:设置最多显示多少刻度,会自动选择显示的刻度,实际值小于等于 nticks,只有 tickmode 为 'auto' 时,才有效。大于等于0的整数。tick0:设置此轴上第一个显示的刻度位置,搭配 dtick 共同使用。如果坐标轴的类型为 ‘log’,那么你传入的应该是取 ‘log’ 后的值;如果坐标轴类型为 ‘date’,那么传入的值也应该为日期字符串;如果坐标轴类型为 ‘category’,那么应该传入一个整数,从0开始,按出现顺序排列。dtick:设置显示刻度的步长,搭配 tick0 共同使用。必须为一个正整数,或者一个字符串(当坐标轴类型为 ‘date’ 或 ‘log’ 时)。tickvals:显示列表中出现的刻度。只有当 tickmode 为 'array'时有效,与 ticktext 搭配使用。
列表、numpy数组、pandas Series。值为数字、字符串或日期 ticktext:用于替换 tickvals 的刻度标签,与 tickvals 一一对应。例如 tickvals=[1, 2] 且 ticktext=['a', 'b'] 那么坐标轴上 1 刻度位置的标签将显示 ‘a’,而不是1,类似的 2刻度显示的标签为 ‘b’。
列表、numpy数组、pandas Series。值为数字、字符串或日期 tickfont:设置刻度标签的字体。字典类型,可用参数如下:
color:字体颜色family:字体size:字体大小 tickangle:刻度标签的水平倾斜角度。
fig = go.Figure()
fig = fig.set_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4], y=[4, 8, 6, 2]
), row=1, col=1)
fig.add_trace(go.Bar(
x=[1, 2, 3, 4], y=[4, 8, 6, 2],
marker_color=['blue', 'yellow', 'blue', 'green']
), row=1, col=2)
fig.update_layout(
xaxis=dict(
linecolor='green',
ticks='inside',
tickwidth=3,
ticklen=10,
tickcolor='red',
tickmode='array',
tickvals=[1, 2, 3, 4],
ticktext=['A', 'B', 'C', 'D'],
),
yaxis=dict(
tickmode='linear',
tick0=2,
dtick=3,
),
xaxis2=dict(
linecolor='red',
tickprefix='Eloik',
tickfont={'size': 16, 'color': '#9fa0d7'},
tickangle=-45,
),
yaxis2=dict(
showticklabels=False,
)
)
fig.write_image('../pic/axes_2.png', scale=10)
fig.show()
autorange:是否根据输入数据自动调整坐标轴的范围。如果 range 指定了,那么 autorange 值变为 False
可取 True、False 或 'reversed' (翻转坐标轴) fixedrange:设置该坐标轴是否可以缩放,如果为 True,则不可以缩放,默认值为 Falserange:设置该坐标轴的范围。如果坐标轴的类型为 ‘log’,那么你必须传入取过 ‘log’ 后的范围(例如:期望显示范围为[1, 100],那么在 log 坐标类型中,输入的值应该是 [0, 2]);如果坐标轴类型为 ‘date’,那么传入的范围也应该是日期字符串;如果坐标轴类型为 ‘category’,那么传入的范围应该是整数,从0开始,按出现的先后顺序递增。
列表,两个值 rangemode:如果为 'normal',则坐标轴范围按照输入数据的极值进行计算;如果为 'tozero' ,无论输入数据的范围是多少,都会显示 0 刻度;如果为 nonnegative,无论输入数据如何,都只显示非负半轴。只有 ‘linear’ 类型的坐标轴才可以使用该参数。tickformat:设置刻度标签的格式。对于数值型,见:https://github.com/d3/d3-format/tree/v1.4.5#d3-format;对于日期型,见:https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format。对于日期型额外添加了两个条目:%h表示半年,%{n}f 表示秒保留n位小数,例如 ‘2016-10-13 09:15:23.456’ 使用格式 ‘%H~%M~%S.%2f’ 将变为 ‘09~15~23.46’exponentformat:设置刻度标签的指数显示规则。例如,考虑数字 1,000,000,000。如果为 None,则表现为 ,1,000,000,000;如果为 'e',表现为 1e+9;如果为 'E',表现为 1 × 1 0 9 1×10^9 1×109;如果为 'power',表现为 1x10^9;如果为 'SI',表现为 1G,如果为 'B',表现为 1B
可取 None、'e'、'E'、'power'、'SI'、'B' minexponent:为 10^n 隐藏 SI 前缀,如果 |n| 小于 minexponent。只有当 exponentformat 为 'SI' 或 'B'时有效separatethousands:是否使用千分隔,如果为 True,那么每四位数字会被分隔
fig = px.line(x=np.linspace(-10, 10, 100), y=(np.random.rand(100) - 0.5) * 200000)
fig.update_layout(
xaxis=dict(
range=(-11, 11),
tickformat='.2f',
),
yaxis=dict(
exponentformat='power',
)
)
fig.write_image('../pic/axes_3.png', scale=10)
fig.show()
color:一次性设置坐标轴线、字体、刻度线和网格的颜色。网格的颜色会与背景混合而变浅。可以被指定的单个属性值覆盖。mirror:决定是否将坐标轴 和(或)刻度镜像到绘图区域的另一侧。如果为 True,则坐标轴线被镜像;如果为 'ticks' ,则坐标轴线和刻度都被镜像;如果为 False,不使用镜像功能;如果为 'all',坐标轴线会在所有共享该坐标轴的子图上镜像;如果为 'allticks',坐标轴线和刻度会在所有共享该坐标轴的子图上镜像。
可取 True、False、'ticks'、'all'、'allticks'
fig = px.line(
x=['abcdefghijklmn', 2, 3, 4], y=[4, 8, 6, 2]
)
fig.add_trace(go.Bar(
x=['abcdefghijklmn', 2, 3, 4], y=[2, 6, 4 ,1]
))
fig.update_layout(
xaxis=dict(
type='category',
showline=True,
linecolor='black',
linewidth=2,
mirror=True,
color='#e60039',
),
yaxis=dict(
showline=True,
linecolor='black',
linewidth=2,
mirror=True,
color='#e60039',
),
width=600, height=400,
showlegend=False,
)
fig.write_image('../pic/axes_4.png', scale=10)
fig.show()
tickson:设置刻度线和网格线相对于其对应的标签的绘画方式。只有坐标轴类型为 'category' 或 'multicategory' 时才有效。当设为 'boundaries'时,刻度线和网格线会显示在两个类别标签中间的位置。
字符串枚举类型,可取:'labels'(默认值)、'boundaries' ticklabelposition:设置刻度标签在坐标轴的哪里显示。注意 top 和 bottom 对 x轴 或 ticklabelmode='period'时无效,同样地,left 和 right 对 y轴 或 ticklabelmode='period' 时无效。当坐标轴类型为 ‘multicategory’ ,且 tickson='boundaries' 时无效。
可取:'outside'(默认值)、'inside'、'outside top'、'inside top'、'outside left'、'inside left'、'outside right'、'inside right'、'outside bottom'、'inside bottom' ticklabelmode:设置刻度标签显示位置的模式。只有坐标轴类型为 ‘date’ 时,'period'才有效,此时刻度标签会显示在两个刻度中间。
可取 'instant'(默认值)、'period'
fig = px.line(
x=['2001', '2002', '2003', '2004'], y=[4, 8, 6, 2]
)
fig.add_trace(go.Bar(
x=['2001', '2002', '2003', '2004'], y=[2, 6, 4 ,1]
))
fig.update_layout(
xaxis=dict(
type='category',
showgrid=True,
tickson='boundaries',
ticks='inside', tickwidth=3, ticklen=10,
),
yaxis=dict(
showline=True,
ticklabelposition='inside top',
),
width=600, height=400,
showlegend=False,
)
fig.write_image('../pic/axes_5.png', scale=10)
fig.show()
domain:设置坐标轴的域(长度)。[0, 1]之间的浮点数categoryorder:设置类别标签的顺序。默认值为 'trace',即根据给定数据的先后顺序排列;取 'category ascending' 或 'category descending' 时,将按照标签名的字典序排列;取 'array' 时,将使用 categoryarray 的顺序进行排列,如果某个标签没有在 categoryarray 中出现,那么将更改为 'trace' 模式;取'total ascending'或 'total descending' 时,将按照值的大小排序。
可取 'trace'、'category ascending'、'category descending'、'array'、'total ascending'、'total descending'、'min ascending'、'min descending'、'max ascending'、'max descending'、'sum ascending'、'sum descending'、'mean ascending'、'mean descending'、'median ascending'、'median descending' categoryarray:设置类别标签的排列顺序,只有 categoryorder='array' 时有效。
fig = px.line(
x=['2001', '2002', '2003', '2004'], y=[4, 8, 6, 2]
)
fig.add_trace(go.Bar(
x=['2001', '2002', '2003', '2004'], y=[2, 6, 4 ,1]
))
fig.update_layout(
xaxis=dict(
type='category',
showgrid=True,
categoryorder='array',
categoryarray=['2003', '2002', '2001', '2004']
),
width=600, height=400,
showlegend=False,
)
fig.write_image('../pic/axes_6.png', scale=10)
fig.show()
rangeslider:在x轴下方添加一个滑动条,字典类型,可选属性如下:
autorange:是否根据输入数据自动调整范围,如果 range 给定,那么该参数自动变为 Falsebgcolor:设置滑动条的背景颜色bordercolor:设置滑动条边框的颜色borderwidth:设置滑动条边框的宽度range:设置滑动条的范围。如果坐标轴的类型为 ‘log’,那么你必须传入取过 ‘log’ 后的范围(例如:期望显示范围为[1, 100],那么在 log 坐标类型中,输入的值应该是 [0, 2]);如果坐标轴类型为 ‘date’,那么传入的范围也应该是日期字符串;如果坐标轴类型为 ‘category’,那么传入的范围应该是整数,从0开始,按出现的先后顺序递增。thickness:设置滑动条的高度,[0, 1]之间的浮点数visible:是否显示滑动条,如果设为 True,那么 y 轴将无法缩放,相当于 fixedrange=True
fig = px.line(x=np.linspace(-10, 10, 100), y=(np.random.rand(100) - 0.5) * 2)
fig.update_layout(
xaxis=dict(
range=(-11, 11),
rangeslider=dict(
visible=True,
bgcolor='#c5c5c5',
bordercolor='#888888',
borderwidth=2,
)
)
)
fig.write_image('../pic/axes_3.png', scale=10)
fig.show()
anchor:如果给定一个其他轴的id(例如 ‘x2’, ‘y’),这个坐标轴将会绑定到垂直于那个轴的坐标轴;如果为 free,那么该轴位置由 position 确定position:设置坐标轴的位置,只有 anchor='free'时有效
[0, 1] 之间的浮点数 showspikes:当鼠标划过图中的数据点时,是否显示一条竖直的线。spikecolor:竖直线的颜色spikethickness:竖直线的宽度spikedash:竖直线线条的样式
可取 'solid'、 'dot'、 'dash'、 'longdash'、 'dashdot'、 'longdashdot'或者一个 dash 长度列表,如:5px、10px、2px、2px spikesnap:设置该竖直线什么时候显示。取'data'时,当鼠标靠近数据点时就会显示;取'cursor'时,只要鼠标放在图上就会显示;取'hovered data'时,当鼠标悬停在数据点时才会显示。
可取 'data'、'cursor'、'hovered data'(默认值) spikemode:设置竖直线的模式。如果为 'toaxis',竖直线从数据点开始向坐标轴方向显示,到达坐标轴停止;如果为 'across',竖直线将贯穿整个绘图区域;如何为 marker, 则在坐标轴上标记点。
可取 'toaxis' 、'across'、marker,可以使用 + 组合这三个值
fig = px.line(
x=[1, 2, 3, 4], y=[4, 8, 6, 2]
)
fig.update_xaxes(
rangemode='tozero',
showspikes=True,
spikemode='toaxis+marker',
spikecolor='red',
spikedash='longdash',
spikesnap='data',
spikethickness=5,
position=0.2,
anchor='free',
)
fig.update_yaxes(
rangemode='tozero',
)
fig.show()



