plotly:get 直方图的值 / plotly:get 轨迹的值

plotly:get the values from a histogram / plotly:get the values from a trace

在 plotly 中,我可以创建一个直方图,例如in this example code from the documentation:

import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()

结果是:

我的问题是如何获取直方图的数据值?据我所知,这个问题应该等同于如何访问跟踪的值? (google 两者都没有帮助)

我可以使用 numpy 重做直方图:

import numpy as np
np.histogram(df.total_bill)

但这并不总是产生相同的存储桶,而且它正在重新进行所有有时用于创建直方图的昂贵计算。

在同一个 Plotly Histogram 文档中,有一个名为 Accessing the counts yaxis values 的部分,它解释了 y 值是在图形呈现时由浏览器中的 JavaScript 计算的,因此您不能在图形对象中访问它(例如,通过 fig.layoutfig.data,您可以尝试其他类型的图表)

他们建议使用 np.histogram 自行计算计数和分箱,然后将这些值传递给 px.bar 以确保您的直方图与您预期的分桶匹配。

我对你的问题的理解是,你希望获得直方图中显示的确切间隔和计数。对于 px.data.tips() 的较小子集,这个:

从图表上读出这些值将是:

counts = [2, 4, 3, 1]
bins = [5, 15, 25, 35, 45]

没有直接方法可以做到这一点,但这并不意味着它不可能。至少如果你愿意使用很棒的 fig.full_figure_for_development()little numpy.

代码亮点(最后的完整片段)

xbins = f.data[0].xbins
plotbins = list(np.arange(start=xbins['start'], stop=xbins['end']+xbins['size'], step=xbins['size']))
counts, bins = np.histogram(list(f.data[0].x), bins=plotbins)

输出:

[2 4 3 1] [ 5 15 25 35 45]

全部详情:

我猜您喜欢能够做到的是:

运行:

fig.data[0].count

并得到:

[2, 4, 3, 1]

但最接近的是:

运行:

fig.data[0].x

并得到:

[15.53, 10.07, 12.6 , 32.83, 35.83, 29.03, 27.18, 22.67, 17.82,
   18.78]

这些只是来自输入的原始值df['total_bill'].tail(10)。所以 DerekO 是正确的,其余部分由 javascript 处理。但是 fig.full_figure_for_development() 会:

[...] return a new go.Figure object, prepopulated with the same values you provided, as well as all the default values computed by Plotly.js, to allow you to learn more about what attributes control every detail of your figure and how you can customize them.

所以运行f = fig.full_figure_for_development(warn=False),然后:

f.data[0].xbins

会给你:

histogram.XBins({
    'end': 45, 'size': 10, 'start': 5
})

现在你已经知道了,可以用一点 numpy 在你的图中得到相同的值:

完整代码:

import plotly.express as px
import numpy as np

df = px.data.tips()
df = df.tail(10)
fig = px.histogram(df, x="total_bill")
f = fig.full_figure_for_development(warn=False)

xbins = f.data[0].xbins
plotbins = list(np.arange(start=xbins['start'], stop=xbins['end']+xbins['size'], step=xbins['size']))
counts, bins = np.histogram(list(f.data[0].x), bins=plotbins)
print(counts, bins)

经过一些证明,我得出的结论是使用groupby可以得到y轴的直方图值。您可以使用 total_bill 值生成自己的数据框,并像这样计算每个值:

import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill")
fig.show()
print(df.groupby('total_bill').total_bill.agg('count').to_frame('COUNT').reset_index().head())



          total_bill  COUNT
 0          3.07      1
 1          5.75      1
 2          7.25      2
 3          7.51      1
 4          7.56      1

我想 plotly 做了类似的事情,然后添加一些其他分组以在每个直方图条中将特定范围内的值堆叠在一起。