Python Matplotlib:指定直方图中的bin值格式';勾号标签

Python Matplotlib:指定直方图中的bin值格式';勾号标签,python,matplotlib,histogram,Python,Matplotlib,Histogram,我正在通过指定数据集的确切仓位自定义数据集的柱状图,我想知道如何将x-tick标签的格式设置为小数点后2位,这在处理子批次时特别有用 当间隔值只有几个小数位时,以下代码运行良好: 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),

我正在通过指定数据集的确切仓位自定义数据集的柱状图,我想知道如何将x-tick标签的格式设置为小数点后2位,这在处理子批次时特别有用

当间隔值只有几个小数位时,以下代码运行良好:

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()

但当它们有大量的小数位时,这就变成:


例如,使用
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()