matplotlib 如何设置x轴标签值而不影响图形?

jvidinwx  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(163)

假设我有一个Pandas Dataframe ,有几千行长,我想用Matplotlib来绘制它们。

  1. temps = df['temperature']
  2. plt.plot(temps)

我希望x轴沿着的值从0开始,以25结束。如下所示:

  1. |
  2. |
  3. |
  4. |
  5. |
  6. |
  7. |________________________
  8. 0 5 10 15 20 25

我该怎么做才不会影响我的计划?

xienkqul

xienkqul1#

设置xlim

您可以使用plt.xlim函数。

  1. temps = df['temperature']
  2. plt.plot(temps)
  3. plt.xlim(0, 25)

但是matplotlib文档要求每个人都使用面向对象的API,并且远离高级的plt绘图函数。

  1. temps = df['temperature']
  2. fig, ax = plt.subplots()
  3. ax.plot(temps)
  4. ax.set_xlim(0, 25)

设置xticks

现在,如果您想要控制沿着x轴的刻度数,您可以手动设置它们,如下所示:

  1. fig, ax = plt.subplots()
  2. ax.plot(temps)
  3. ax.set_xlim(0, 25)
  4. ax.set_xticks([0, 5, 10, 15, 20, 25])

也可以使用.ticker API如下所示:

  1. import matplotlib.pyplot as plt
  2. from matplotlib.ticker import MultipleLocator
  3. temps = [i ** 2 for i in range(25)]
  4. fig, ax = plt.subplots()
  5. ax.plot(temps)
  6. ax.set_xlim(0, 25)
  7. # from the lower x-limit to the upper x-limit
  8. # place a tick every multiple of 5
  9. ax.xaxis.set_major_locator(MultipleLocator(5))

使用多个值

如果您有超过25个值,并希望将它们放置在0-25的任意范围内,则可以使用刻度定位器和刻度格式化器,如下所示:

  1. import matplotlib.pyplot as plt
  2. from matplotlib.ticker import LinearLocator
  3. temps = [i ** 2 for i in range(1_000)]
  4. fig, ax = plt.subplots()
  5. ax.plot(temps)
  6. ax.margins(x=0)
  7. n = 6 # ticks including: 0, 5, 10, 15, 20, 25
  8. ax.xaxis.set_major_locator(LinearLocator(n))
  9. ax.xaxis.set_major_formatter(lambda val, pos: pos * (n - 1))

展开查看全部

相关问题