Matplotlib增加x轴上点之间的间距

2024-09-22 14:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种防止标签重叠的方法。在Stackoverflow中搜索时,我甚至找不到任何关于如何控制x轴间距的建议。

enter image description here

        matplotlib.pyplot.xticks(x, xticks, rotation=90)
        matplotlib.pyplot.plot(x, y)
        matplotlib.pyplot.bar(x, y, alpha=0.2)

        matplotlib.pyplot.title(
            f"średnia cena produktu {self.identifier}, według kontrahentów")
        matplotlib.pyplot.xlabel("kontrahent")
        matplotlib.pyplot.ylabel("cena")


        matplotlib.pyplot.tight_layout()

        matplotlib.pyplot.savefig(os.path.join(
            "products", self.identifier, "wykres.png"))
        matplotlib.pyplot.close()

Tags: 方法selfplotmatplotlibbar标签stackoverflow建议
1条回答
网友
1楼 · 发布于 2024-09-22 14:26:48

首先,如果没有你的数据,很难知道到底发生了什么,所以我不得不创建虚拟数据,并调整变量“self.identifier”和“xticks”,因为我们不知道它们是什么。

也就是说,你要找的功能是

plt.tick_params(axis='x', which='major', labelsize=__)

如下代码所示:

import numpy as np
import matplotlib.pyplot as plt

#make dummy data
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]
y=np.random.rand(len(x))

plt.figure()
plt.plot(x, y)
plt.bar(x, y, alpha=0.2)
plt.title(f"średnia cena produktu, według kontrahentów")
plt.xlabel("kontrahent")
plt.ylabel("cena")
plt.xticks(x, [str(i) for i in y], rotation=90)

#set parameters for tick labels
plt.tick_params(axis='x', which='major', labelsize=3)

plt.tight_layout()

相关问题 更多 >