Plotly散点图趋势线出现在散点下方。如何让趋势线出现在散点图上方?[Python]

4

我正在尝试为Plotly散点图绘制趋势线,但是我无法弄清如何让趋势线出现在散点图上方。以下是我使用的代码:

import plotly.express as px 
fig = px.scatter(df, x='Percentage_LIFT', y='Average_Daily_Contacts', 
                 title='Percent on LIFT vs Average Daily Contacts', 
                 trendline = "ols", trendline_color_override="red")
fig.show()

这是代码生成的散点图:

enter image description here

如何使趋势线显示在散点图上方?


我的建议对你有用吗? - vestland
1
不幸的是,它没有改变图表。虽然感谢您的建议!最终我使用了seaborn来绘制图表。 - noha54
如果那没有改变图形,那么您需要分享一份数据样本以使提供的代码片段具有可复制性。如果您认为问题已经解决,您是否考虑将我的建议标记为接受的答案? - vestland
1个回答

2

使用px.scatter时,我没有看到相同的行为。但只要你只有一个迹线显示散点,一个迹线显示趋势线,您可以使用以下内容切换数据在图形对象中出现的顺序:

fig.data = fig.data[::-1]

这样做将把这个:

enter image description here

变成这样:

enter image description here

完整代码:

# imports
import pandas as pd
import plotly.express as px

# data
df = px.data.stocks()[['GOOG', 'AAPL']]

# your choices
target = 'GOOG'

# plotly
fig = px.scatter(df, 
                 x = target,
                 y = [c for c in df.columns if c != target],
                 template = 'plotly_dark',
                 trendline = 'ols',
                 title = "fig.update_traces(mode = 'lines')",
                 trendline_color_override='red')

fig.data = fig.data[::-1]
fig.show()

这会重新排列图例(趋势线首先出现在图例中,而不是最后),但似乎不会改变图表。Plotly 5.18.0。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接