Python:matplotlib 的自适应 xticks

Python: Adaptive xticks for matplotlib

晚上好

为了进行编码练习,我正在使用 matplotlib 生成绘图。设 f 为实值函数(这对我的问题不重要)。随着 n(数据量)变大,我现在遇到了 xticks 间距的问题。你知道如何让这个自适应到一定程度吗?

import matplotlib.pyplot as plt
import numpy as np

n = # positive integer, specified by user in console

x = [m for m in range(1,n+1)]
y = [f(i) for i in x]

plt.plot(x, y)
plt.title("Berechnungszeitdiagramm für die Funktion")
plt.xlim(1,n)
plt.xticks([i for i in range(1,n+1)])
plt.xlabel("n")
plt.ylim(0,np.max(vector)+1)
plt.ylabel("Berechnungszeit (in ns)")
plt.grid()

为了说明我的问题,请考虑以下生成图的 x 轴:

Plot for n=15

Plot for n=100

我想你可以在 plt.xticks 中编辑你的列表理解,如下所示:

plt.xticks([i for i in range(1, n+1, stepsize)])

其中 stepsize 是一个整数。如果你总是想要 15 个刻度,你可以设置 stepsize = n // 15 例如