【问题标题】:Python: Adaptive xticks for matplotlibPython:matplotlib 的自适应 xticks
【发布时间】:2021-03-06 17:02:06
【问题描述】:

晚上好

对于编码练习,我正在使用 matplotlib 生成绘图。让 f 是一个实值函数(这对我的问题并不重要)。我现在的 xticks 间距有问题,因为 n(数据量)变大了。你知道如何让它在一定程度上适应吗?

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

【问题讨论】:

    标签: python matplotlib plot xticks


    【解决方案1】:

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

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

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

    【讨论】:

    • 有没有办法从给定的数据列表长度中提取 stepsize 参数?我不想手动指定这个,而是将间距计算为我的 x 长度的函数。
    • 我已将其添加到我的答案中。如果 n 不总是 x 的长度,您也可以将 n 替换为 len(x)
    • 谢谢!这很好。 :D
    • 不客气。如果这回答了您的问题,只需将答案标记为解决方案,这样任何有类似问题的人都可以从中受益。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 2018-02-27
    • 2020-09-03
    • 2019-08-19
    • 1970-01-01
    相关资源
    最近更新 更多