gpt4 book ai didi

python - Plotly:如何显示边际直方图计数以外的其他值?

转载 作者:行者123 更新时间:2023-12-04 14:09:00 27 4
gpt4 key购买 nike

我正在尝试在原始图上方创建一个链接的边缘图,具有相同的 x 轴但具有不同的 y 轴。
我在 plotly.express 看到过包中有 4 个选项,您可以在其中在散点图上创建 margin_x 图,但它们都基于与 x 和 y 相同的列。
就我而言,我在 x 轴上有一个日期,在 y 轴上有某物的比率,我正在尝试生成该比率所基于的样本的直方图边际分布图(位于样本列中df)。
我在不减少任何重要细节的情况下简化了我的尝试:

import pandas as pd
import plotly.express as px

df = pd.DataFrame(
{
"date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")],
"rate": [0.88, 0.96],
"samples": [130, 1200])
}
)

fig = px.scatter(df, x='date', y='rate', marginal_x='histogram')
fig.show()
我基于的文档: https://plotly.com/python/marginal-plots/
我想要的结果:
Example:
enter image description here
不同之处在于我使用了聚合 df,所以我的计数仅为 1,而不是样本数量。
有任何想法吗?
谢谢!

最佳答案

我明白你的说法

[...] and rate of something on my y-axis


... 表示您想在直方图上显示一个不算数的值。 marginal_x='histogram'px.scatter()似乎默认只显示计数,这意味着没有直接的方法来显示单个观察的值。但如果你愿意使用 fig = make_subplots()结合 go.Scatter()go.Bar() ,那么你可以轻松地构建这个:
阴谋
enter image description here
完整代码:
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, cols=1,
row_heights=[0.2, 0.8],
vertical_spacing = 0.02,
shared_yaxes=False,
shared_xaxes=True)

df = pd.DataFrame(
{
"date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")],
"rate": [0.88, 0.96],
"samples": [130, 1200]
}
)

fig.add_trace(go.Bar(x=df['date'], y=df['rate'], name = 'rate'), row = 1, col = 1)

fig.update_layout(bargap=0,
bargroupgap = 0,
)

fig.add_trace(go.Scatter(x=df['date'], y=df['samples'], name = 'samples'), row = 2, col = 1)
fig.update_traces(marker_color = 'rgba(0,0,250, 0.3)',
marker_line_width = 0,
selector=dict(type="bar"))

fig.show()

关于python - Plotly:如何显示边际直方图计数以外的其他值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66030470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com