[英]Matplotlib: Specify format of bin values in a histogram's tick labels
我通过指定其确切的 bin 来定制数据集的直方图,我想知道如何将 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)
设置更高的图形高度是一种可能的解决方法,但不能解决问题。 有没有一种优雅的方法来设置 bin 中显示的小数位数?
您必须自己格式化间隔索引,然后设置标签:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.