如何重用matplotlib.Axes.hist的返回值? [英] How to re-use the return values of matplotlib.Axes.hist?

查看:0
本文介绍了如何重用matplotlib.Axes.hist的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要将同一数据的直方图绘制两次:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,6))
ax1,ax2 = fig.subplots(nrows=2,ncols=1)
ax1.hist(foo)
ax2.hist(foo)
ax2.set_yscale("log")
ax2.set_xlabel("foo")
fig.show()

请注意,我调用了Axes.hist两次,这可能很昂贵。我想知道是否有一种简单的方法可以重复使用第一个调用的返回值以降低第二个调用的成本。

推荐答案

ax.hist文档中,有一个相关的重用np.histogram输出的示例:

weights参数可用于绘制已入库的数据的直方图,方法是将每个bin视为权重等于其计数的单个点。

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

我们可以对ax.hist使用相同的方法,因为它还返回计数和箱子(以及条形图容器):

x = np.random.default_rng(123).integers(10, size=100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))

counts, bins, bars = ax1.hist(x)          # original hist
ax2.hist(bins[:-1], bins, weights=counts) # rebuilt via weights params


或者,使用ax.bar重建原始直方图并重新设置宽度/对齐方式以匹配ax.hist

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))

counts, bins, bars = ax1.hist(x)                    # original hist
ax2.bar(bins[:-1], counts, width=1.0, align='edge') # rebuilt via ax.bar

这篇关于如何重用matplotlib.Axes.hist的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆