我试图让这条线显示在栏上。似乎任何痕迹都有secondary_y=True
将绘制在 secondary_y=False
的顶部.
这很好,但是对于这个特定的数据集,条形轴应该在右边,否则这个图会让人困惑。线是在 1-3 范围内的那条线,而条是在 0-35k 范围内的那条线。
换句话说,它应该看起来像这样,但 y 轴已切换。有什么方法可以切换轴,或控制绘制轨迹的顺序,以便我可以强制线条位于条形图的顶部?
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from plotly.offline import init_notebook_mode, plot
init_notebook_mode()
rdf = pd.read_csv('us_covid_data_latest.csv', dtype={'fips':str})
incidence = pd.pivot_table(rdf, values='cases', index = 'date', aggfunc=np.sum)
incidence['actual_inc'] = incidence['cases'].diff()
def tail_plot_plotly(tail):
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Bar(
x= incidence['date'].tail(tail),
y= incidence['actual_inc'].tail(tail)
),
secondary_y = False
)
fig.add_trace(
go.Scatter(
x= incidence['date'].tail(tail),
y= incidence['R_t'].tail(tail)
),
secondary_y = True
)
plot(fig)
tail_plot_plotly(50)
最佳答案
在没有数据集样本的情况下提供完整的解决方案并不容易,但我仍然认为我已经弄清楚了。我现在有点赶时间,所以我会简短地说:
条是大数字,线是小数字。开箱即用 fig = make_subplots(specs=[[{"secondary_y": True}]])
将提供:
Line trace on top = Good. Bar numbers to the left = Bad.
更改 yoy 将不同轨迹应用于图形的顺序无济于事。但是您可以自由指定您希望主 y 轴和辅助 y 轴显示在图的哪一侧,如下所示:
fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))
将其添加到组合中,您将获得:Line trace on top = Good. Bar numbers to the right = Good.
带数据样本的完整代码:
# imports
import plotly.graph_objects as go
import numpy as np
from plotly.subplots import make_subplots
# set figure twith multiple y axes
fig = make_subplots(specs=[[{"secondary_y": True}]])
# blue line with numbers from 1 to 3
fig.add_trace(
go.Scatter(x=[0, 1, 2, 3, 4, 5],
y=[1.5, 1.0, 1.3, 2.7, 1.8, 2.9]),secondary_y=True)
# red bars with big numbers
fig.add_trace(
go.Bar(x=[0, 1, 2, 3, 4, 5],
y=[np.nan, np.nan, np.nan, 100000, 20000, 250000]))
# update layout to put axes and values in the desired positions
fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))
fig.show()
关于python - Plotly:如何更改跟踪顺序,或在 plotly 中切换轴的边?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61402079/