绘图matplotlib djang顶部的空白

2024-04-26 22:51:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于matplotlib条的问题。 我已经做了一些条形图,但我不知道为什么,这张图在顶部留下了巨大的空白。在

代码类似于我制作的其他图形,他们没有这个问题。在

如果有人有任何想法,我很感激你的帮助。在

x = matplotlib.numpy.arange(0, max(total))
ind = matplotlib.numpy.arange(len(age_list))

ax.barh(ind, total)

ax.set_yticks(ind) 
ax.set_yticklabels(age_list)

Tags: 代码numpy图形agelenmatplotlibaxmax
1条回答
网友
1楼 · 发布于 2024-04-26 22:51:17

你说的“顶部空白”是指y限制设置得太大吗?在

默认情况下,matplotlib将选择x和y轴限制,以便将它们四舍五入到最接近的“偶数”(例如1、2、12、5、50、-0.5等)。在

如果要设置轴限制,使其在绘图周围“紧”(即数据的最小值和最大值),请使用ax.axis('tight')(或等效地,plt.axis('tight'),它将使用当前轴)。在

另一个非常有用的方法是plt.margins(...)/ax.margins()。它的行为类似于axis('tight'),但会在限制周围留下一些填充。在

作为您问题的一个例子:

import numpy as np
import matplotlib.pyplot as plt

# Make some data...
age_list = range(10,31)
total = np.random.random(len(age_list))
ind = np.arange(len(age_list))

plt.barh(ind, total)

# Set the y-ticks centered on each bar
#  The default height (thickness) of each bar is 0.8
#  Therefore, adding 0.4 to the tick positions will 
#  center the ticks on the bars...
plt.yticks(ind + 0.4, age_list)

plt.show()

Auto-rounded y-axis limits

如果我希望限制更严格,我可以在调用plt.barh之后调用plt.axis('tight'),这将给出:

Tight axis limits

但是,您可能不希望事情过于紧凑,所以可以使用plt.margins(0.02)在所有方向添加2%的填充。然后可以使用plt.xlim(xmin=0)将左侧限制设置回0:

^{pr2}$

这会让情节更精彩:

Nicely padded margins

希望这能给你指明正确的方向,无论如何!在

相关问题 更多 >