在matplotlib django的情节顶部的空白区域

pso*_*res 2 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_list)
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 6

"顶部的空白"是指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()
Run Code Online (Sandbox Code Playgroud)

自动舍入的y轴限制

如果我希望限制更严格,我可以在通话plt.axis('tight')后拨打电话plt.barh,这会给:

紧轴限制

但是,您可能不希望事情太紧张,因此您可以使用plt.margins(0.02)在所有方向添加2%填充.然后,您可以使用以下命令将左侧限制设置回0 plt.xlim(xmin=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()
Run Code Online (Sandbox Code Playgroud)

这会产生更好的情节:

很好的填补利润

希望无论如何,这指向了正确的方向!