Python 绘图matplotlib django顶部的空白
我有一个关于matplotlib条的问题。 我已经做了一些条形图,但我不知道为什么,这一个在顶部留下了巨大的空白 代码类似于我制作的其他图形,它们没有这个问题 如果有人有任何想法,我感谢你的帮助Python 绘图matplotlib django顶部的空白,python,django,matplotlib,Python,Django,Matplotlib,我有一个关于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
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)
“顶部空白”是指y限制设置得太大吗
默认情况下,matplotlib将选择x轴和y轴限制,以便将它们四舍五入为最接近的“偶数”(例如,1、2、12、5、50、-0.5等)
如果要设置轴限制,使其在绘图周围“紧密”(即数据的最小值和最大值),请使用ax.axis('tight')
(或等效地使用当前轴的plt.axis('tight')
)
另一个非常有用的方法是plt.margins(…)
/ax.margins()
。它的作用类似于轴(“紧”),但会在限制周围留下一些填充
作为您问题的一个例子:
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()
如果我希望限制更严格,我可以在调用plt.barh
之后调用plt.axis('tight')
,这将给出:
但是,您可能不希望内容太紧,因此可以使用plt.margins(0.02)
在所有方向上添加2%的填充。然后,您可以使用plt.xlim(xmin=0)
将左侧限制设置回0:
这会产生一个更好的情节:
无论如何,希望这能为你指明正确的方向 非常感谢!我有一个像你画的第一个图形,在做了修改后,我能看到一个与你的类似的!你解释得很好,很有道理:)
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))
height = 0.8
plt.barh(ind, total, height=height)
plt.yticks(ind + height / 2.0, age_list)
plt.margins(0.05)
plt.xlim(xmin=0)
plt.show()