【发布时间】:2026-01-15 16:05:02
【问题描述】:
我正在尝试制作一个漂亮的条形图,但遇到了以下问题:
- 水平网格线在条的前面,尽管我尝试了
ax.grid的各种zorder参数。我怎样才能把网格放到后面? - 紧的布局不紧。我试过
fig.tight_layout()和plt.tight_layout()。如何自动裁剪图片的所有面? - 有没有办法定位 xTick 文本,以便每个“longText”与其 xTick 对齐?
import matplotlib.pyplot as plt
def show_mountains(bins, fortyfive=False):
fig, ax = plt.subplots()
ax.grid(axis='y', zorder=-100, linewidth=0.2)
fig.tight_layout()
xTicks = list(range(len(bins)))
if fortyfive:
plt.xticks(rotation=45)
ax.set_xticks(xTicks)
ax.set_xticklabels(["longText"]*len(bins), fontsize=13)
plt.bar(xTicks, bins, width=0.65, color="#6186f1")
plt.tight_layout()
plt.close()
domain_bins = [52, 47, 36, 15, 14, 11, 18]
show_mountains(domain_bins, True)
【问题讨论】:
-
对于网格线:
ax.set_axisbelow(True)?你试过plt.tight_layout()的填充参数吗?关于刻度标签旋转,请参阅How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal? -
ax.set_axisbelow(True)效果很好!plt.tight_layout(pad=0, w_pad=0, h_pad=0)也保持了非常紧凑的布局。最后:plt.xticks(rotation=45, ha="right")给出了完美的对齐方式!如果您/其他人尚未开始,我会将其编辑为答案。
标签: python matplotlib