python - Matplotlib:指定直方图刻度标签中 bin 值的格式

标签 python matplotlib histogram

我通过指定精确的数据箱来自定义数据集的直方图,我想知道如何将 x-tick 标签的格式设置为小数点后两位,这在处理子图时特别有用。

当间隔值有几个小数位时,以下代码效果很好:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x = np.random.randn(1000)

intervals  = [(-4, -3.5), (-3.5, -3), (-3, -2.5), (-2.5, -2), (-2, -1.5), (-1.5, -1), (-1, -0.5), (-0.5, 0), (0, 0.5), (0.5, 1), (1, 1.5), (1.5, 2.5), (2.5, 3), (3, 3.5), (3.5, 4)]
bins       = pd.IntervalIndex.from_tuples(intervals)
histogram  = pd.cut(x, bins).value_counts().sort_index()

fig = plt.figure(figsize = (16,8))

plt.subplot(2, 1, 1)
histogram.plot(kind='bar')
plt.title('First subplot')
plt.xlabel('Value')
plt.ylabel('Realisations')

plt.subplot(2, 1, 2)
histogram.plot(kind='bar')
plt.title('Second subplot')
plt.xlabel('Value')
plt.ylabel('Realisations')

plt.show()

enter image description here

但是当它们有很多小数位时,就会变成:

enter image description here

例如,使用 figsize=(16,15) 设置更高的图形高度是一种可能的解决方法,但不能解决问题。是否有一种优雅的方法来设置垃圾箱中显示的小数位数

最佳答案

您必须自己设置间隔索引的格式,然后设置标签:

xtl = [f'({l:.2f}, {r:.2f}]' for l,r in zip(bins.values.left, bins.values.right)]
plt.gca().set_xticklabels(xtl)

示例:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x = np.random.randn(1000)

bins       = pd.IntervalIndex.from_breaks(np.linspace(-4.1234567, 4.1234567, 10))
histogram  = pd.cut(x, bins).value_counts().sort_index()
xtl = [f'({l:.2f}, {r:.2f}]' for l,r in zip(bins.values.left, bins.values.right)]

fig = plt.figure(figsize = (16,8))

plt.subplot(2, 1, 1)
histogram.plot(kind='bar')
plt.title('First subplot')
plt.xlabel('Value')
plt.ylabel('Realisations')
plt.gca().set_xticklabels(xtl)

plt.subplot(2, 1, 2)
histogram.plot(kind='bar')
plt.title('Second subplot')
plt.xlabel('Value')
plt.ylabel('Realisations')
plt.gca().set_xticklabels(xtl)

plt.show()

enter image description here

关于python - Matplotlib:指定直方图刻度标签中 bin 值的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62935231/

相关文章:

python - @staticmethod 或类外函数?

julia - 如何在 Julia 中绘制热图

python - Numpy直方图,如何在每个bin中取最大值

r - 如何在 R 中将密度表示为百分比?

python - Pygame 播放列表在后台连续播放

python - requests.exceptions.ConnectionError : HTTPConnectionPool(host ='127.0.0.1' , 端口 = 8000):超过最大重试次数,网址:/api/1/

python - 如何在 Airflow 中组合多个 DAG

python-3.x - PyCharm 导入错误 : Claims 'matplotlib' is not a package, 但在 IDLE 中成功运行

python - 根据百分位数绘制直方图

python - 在 Python 中绘制随机过程