【问题标题】:Python Pyplot: How to scale x-axis independant from number of list-elements?Python Pyplot:如何独立于列表元素的数量来缩放 x 轴?
【发布时间】:2013-09-13 20:50:53
【问题描述】:

只想绘制一个包含 50 个(实际上是 51 个)元素的列表:从 0 到 50 的列表索引应该代表 x 轴上从 0 到 10 米的米,而每个进一步元素的索引增加 0.2 米。 示例:

list = [2.5, 3, 1.5, ... , 7, 9]
len(list)
>>50

我希望 x 轴从 0 到 10 米绘制,即 (x,y)==(0, 2.5), (0.2, 3), (0.4, 1.5), ..., (9.8, 7), (10, 9)

相反,该列表显然是在从 0 到 50 的 x 尺度上绘制的。 知道如何解决问题吗?谢谢!

【问题讨论】:

标签: python matplotlib scale axis


【解决方案1】:

我会避免将列表对象命名为list。它混淆了命名空间。但是尝试类似

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

x = np.arange(0, 10, 0.2)
y = [2.5, 3, 1.5, ... , 7, 9]
ax.plot(x, y)
plt.show()

它使用np.arange在x轴上创建一个点列表,这些点出现在0.2的倍数处,matplotlib将绘制y值。 Numpy 是一个用于轻松创建和操作向量、矩阵和数组的库,尤其是当它们非常大时。

编辑:

fig.add_subplot(N_row,N_col,plot_number) 是使用 matplotlib 进行绘图的面向对象的方法。如果您想将多个子图添加到同一个图形,这很有用。例如,

ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

将两个子图添加到同一图形fig。它们将排列成两排,一个在另一个之上。 ax2 是底部的子图。查看此relevant post 了解更多信息。

要更改实际的 x 刻度和刻度标签,请使用类似

ax.set_xticks(np.arange(0, 10, 0.5))
ax.set_xticklabels(np.arange(0, 10, 0.5)) 
# This second line is kind of redundant but it's useful if you want 
# to format the ticks different than just plain floats. 

【讨论】:

  • 抱歉回复晚了,谢谢,它工作得很好!仍然存在 2 个问题: - google add_subplot(),但并没有真正得到,它有什么用处。有什么简短的解释吗? - 如何调整刻度标签以使其更精细?默认情况下,x 轴标签为 0、2、4、6、8、10。将它们设置为 0、0.5、1、1.5 等就好了,而实数被描绘得稍微小一些。 Txh 再次为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
相关资源
最近更新 更多