python - 绘图 matplotlib django 顶部的空白

标签 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)

最佳答案

“顶部的空白”是指 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:

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()

这会产生更好的情节:

Nicely padded margins

无论如何,希望这能为您指明正确的方向!

关于python - 绘图 matplotlib django 顶部的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3558950/

相关文章:

django - 预检响应中不允许 Laravel 前端到 Django 后端 x-csrf-token

python - 仅水平网格(在 python 中使用 pandas plot + pyplot)

Python int 太大而无法转换为 C long - 绘制 Pandas 日期

python - 删除 gridspec matlibplot 图的 xticks 和 yticks

python - Discord 机器人检查机器人是否删除了消息

python - 在 Matplotlib 中根据像素值设置透明度

python - 用 Pandas 和 Group By 绘制堆叠直方图

python - 使用 mysql-server 设置 django 时出现异常

django - 关于 Django 中的 IP 0.0.0.0

python - neo4j-python 错误