Fra*_*TEC 9 python matplotlib bar-chart subplot
图形的边框/x 轴与 pyplot 条形图中的第一个和最后一个条形之间有很大的空间(第一张图片中的红色箭头)。在下图中,左图中看起来不错,但右图中浪费了很多空间。图形越大,空间就越大。
\n\n看看第二张图中浪费了多少空间:
\n\n知道如何解决这个问题吗?
\n代码:
\nplt.figure(figsize=figsize)\ngrid = plt.GridSpec(figsize[1], figsize[0], wspace=120/figsize[0])\nplt.suptitle(feature.upper())\n\n# NaN plot\nplt.subplot(grid[:, :2])\nplt.title(\'Pr\xc3\xa9sence\')\nplt.ylabel(\'occurences\')\nplt.bar([0, 1], [df.shape[0] - nan, nan], color=[\'#4caf50\', \'#f44336\'])\nplt.xticks([0, 1], [\'Renseign\xc3\xa9\', \'Absent\'], rotation=\'vertical\')\n\n# Distrib plot\nplt.subplot(grid[:, 2:])\nplt.title(\'Distribution\')\nx_pos = [i for i, _ in enumerate(sizes)]\nplt.bar(x_pos, sizes)\nplt.xticks(x_pos, labels, rotation=\'vertical\')\nplt.show()\nRun Code Online (Sandbox Code Playgroud)\ndf是我的 pandas DataFrame,nan我正在绘制的特征的空值数量,sizes是每个值出现的次数,labels是相应标签的值。
Joh*_*anC 10
您可以使用plt.margins(x=0, tight=True)。
默认边距是0.05,这意味着第一个和最后一个 x 值之间距离的 5% 用作边距。选择一个较小的值,例如plt.margins(x=0-01, tight=True)会留下一点余量,因此条形图看起来不会粘在轴上。
在某些情况下,需要更大的余量。例如,仅绘制两个非常窄的条形时。因此,情节好看的确切价值取决于多种因素以及个人喜好。
请注意,plt.margins最好在最后一个将元素添加到图中的函数之后调用。
另请注意,plt.xlim具有类似的更改绘图限制的功能。这是一个示例,设置xlim轴和条之间的距离与条本身之间的距离相同。
import matplotlib.pyplot as plt
fig, axes = plt.subplots(ncols=3, figsize=(12, 3))
for ax in axes:
width = 0.4
ax.bar([0, 1, 2], [2, 3, 5], width=width, color='turquoise')
if ax == axes[0]:
ax.margins(x=0.01)
ax.set_title('1% margins')
elif ax == axes[1]:
ax.margins(x=0.1)
ax.set_title('10% margins')
else:
ax.set_xlim(-1+width/2, 3-width/2)
ax.set_title('setting xlim')
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4080 次 |
| 最近记录: |