plotly:如何在带有分类 x 轴的带状图中添加不同的垂直线
plotly: how to add different vertical lines in strip plot with categorical x-axis
我有一个带有分类 x 轴的简单带状图。我想为每个类别添加一条垂直线(在不同的 y 值上)。
我可以像这样在整个情节中创建一条垂直线:
import plotly.express as px
fig = px.strip(df, x="category", y="value")
fig.add_hline(y=191)
结果如下所示:
但是,我无法为每个类别绘制一条垂直线。
期望的输出
我想要的输出是这样的:
我尝试在布局中添加一个形状,但它没有影响输出:
fig.update_layout(shapes=[
dict( type= 'line',
yref= 'paper', y0= 180, y1= 180,
xref= 'x', x0= "cat1", x1= "cat1")])
如果 x 轴是数字,这样的方法可能会起作用。但是,不确定如何在此处指定类别。如果这是要走的路,那我可能做错了。
我如何能够添加一条水平线,如上所述,每个类别具有不同的 y 值?
重现情节的数据:
import pandas as pd
df = pd.DataFrame(data={
"category": ["cat1", "cat1", "cat2", "cat2"],
"value": [150, 160, 180, 190]
})
添加带形状的线条。有两种类型的坐标轴:x,y 轴和基于纸张的。从您想要的输出中,您可以读取并将 x 轴指定为基于纸张的,将 y 轴指定为 y 轴值。
import pandas as pd
import plotly.express as px
df = pd.DataFrame({'category':['cat1','cat1','cat2','cat2'],'value':[150,160,180,190]})
fig = px.strip(df, x="category", y="value")
fig.update_layout(shapes=[dict(type='line', x0=0.2, y0=180, x1=0.3, y1=180,
xref='paper', yref='y',
line_width=3, line_color='red'),
dict(type='line', x0=0.7, y0=192, x1=0.8, y1=192,
xref='paper', yref='y',
line_width=3, line_color='red'),
])
fig.show()
我有一个带有分类 x 轴的简单带状图。我想为每个类别添加一条垂直线(在不同的 y 值上)。
我可以像这样在整个情节中创建一条垂直线:
import plotly.express as px
fig = px.strip(df, x="category", y="value")
fig.add_hline(y=191)
结果如下所示:
但是,我无法为每个类别绘制一条垂直线。
期望的输出
我想要的输出是这样的:
我尝试在布局中添加一个形状,但它没有影响输出:
fig.update_layout(shapes=[
dict( type= 'line',
yref= 'paper', y0= 180, y1= 180,
xref= 'x', x0= "cat1", x1= "cat1")])
如果 x 轴是数字,这样的方法可能会起作用。但是,不确定如何在此处指定类别。如果这是要走的路,那我可能做错了。
我如何能够添加一条水平线,如上所述,每个类别具有不同的 y 值?
重现情节的数据:
import pandas as pd
df = pd.DataFrame(data={
"category": ["cat1", "cat1", "cat2", "cat2"],
"value": [150, 160, 180, 190]
})
添加带形状的线条。有两种类型的坐标轴:x,y 轴和基于纸张的。从您想要的输出中,您可以读取并将 x 轴指定为基于纸张的,将 y 轴指定为 y 轴值。
import pandas as pd
import plotly.express as px
df = pd.DataFrame({'category':['cat1','cat1','cat2','cat2'],'value':[150,160,180,190]})
fig = px.strip(df, x="category", y="value")
fig.update_layout(shapes=[dict(type='line', x0=0.2, y0=180, x1=0.3, y1=180,
xref='paper', yref='y',
line_width=3, line_color='red'),
dict(type='line', x0=0.7, y0=192, x1=0.8, y1=192,
xref='paper', yref='y',
line_width=3, line_color='red'),
])
fig.show()