减少 matplotlib 中直方图的 y 刻度间距
Reduce y ticks spacing for histograms in matplotlib
我正在使用 matplotlib
绘制直方图,其中每个 bin 包含 1 个值。这是一个示例:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def image():
# Generate a bunch of random data, here's an example
TYPE1 = [128, 129, 132, 6, 136, 139, 12, 13, 142, 140]
TYPE2 = [18, 147, 148, 23, 152, 26, 154, 156, 157, 158]
TYPE3 = [159, 161, 165, 42, 44, 172, 176, 182, 188, 62]
TYPE4 = [190, 193, 198, 199, 72, 77, 80, 82, 215, 216]
TYPE5 = [218, 223, 95, 226, 101, 106, 108, 109, 113, 127]
fig, ax = plt.subplots(1, 1)
ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.hist([TYPE1, TYPE2, TYPE3, TYPE4, TYPE5],
color=['white', 'white', '0.8', 'green', 'black'],
label=['TYPE1', 'TYPE2', 'TYPE3', 'TYPE4', 'TYPE5'],
stacked=True,
bins=250)
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True)
plt.tight_layout()
plt.show()
如何将 0
和 1
之间的 y 轴间距缩小为实际高度的四分之一,使其看起来如下所示轴?
您可以定义可以使用较小高度的图形尺寸。此外,您不需要再次定义 ax
。我已经注释掉了多余的行。我还会使用关键字 ncol=2
为图例使用 2 列格式。看起来好多了。
fig, ax = plt.subplots(1, 1, figsize=(6, 2.5))
# ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True, ncol=2)
我正在使用 matplotlib
绘制直方图,其中每个 bin 包含 1 个值。这是一个示例:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
def image():
# Generate a bunch of random data, here's an example
TYPE1 = [128, 129, 132, 6, 136, 139, 12, 13, 142, 140]
TYPE2 = [18, 147, 148, 23, 152, 26, 154, 156, 157, 158]
TYPE3 = [159, 161, 165, 42, 44, 172, 176, 182, 188, 62]
TYPE4 = [190, 193, 198, 199, 72, 77, 80, 82, 215, 216]
TYPE5 = [218, 223, 95, 226, 101, 106, 108, 109, 113, 127]
fig, ax = plt.subplots(1, 1)
ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.hist([TYPE1, TYPE2, TYPE3, TYPE4, TYPE5],
color=['white', 'white', '0.8', 'green', 'black'],
label=['TYPE1', 'TYPE2', 'TYPE3', 'TYPE4', 'TYPE5'],
stacked=True,
bins=250)
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True)
plt.tight_layout()
plt.show()
如何将 0
和 1
之间的 y 轴间距缩小为实际高度的四分之一,使其看起来如下所示轴?
您可以定义可以使用较小高度的图形尺寸。此外,您不需要再次定义 ax
。我已经注释掉了多余的行。我还会使用关键字 ncol=2
为图例使用 2 列格式。看起来好多了。
fig, ax = plt.subplots(1, 1, figsize=(6, 2.5))
# ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.legend(loc='upper right', bbox_to_anchor=(1, -0.15), fancybox=True, ncol=2)