【问题标题】:Matplotlib order of the X axis is wrong [duplicate]X轴的Matplotlib顺序错误[重复]
【发布时间】:2018-06-10 21:08:19
【问题描述】:

我正在尝试使用 Matplotlib (following this exact tutorial) 使用 Python 制作实时图表。但是我的代码中 X 轴的顺序是错误的,因为它从 1 开始,到 10,然后是 11,然后回到 2、3、4、5...

我只是复制了教程中的代码和数字,但得到了不同的结果。这是它为我显示的图表:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

def animate(i):

    graph_data = open("animation_file.txt", 'r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:

        if len(line) > 1:

            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

这里是“animation_file.txt”:

1, 5
2, 3
3, 4
4, 7
5, 4
6, 3
7, 6
8, 7
9, 4
10,4
11, 2

【问题讨论】:

  • 您在互联网上找到了一些代码,但您不知道它是如何工作的?你有没有花时间阅读 Matplotlib 文档?您是否排除了代码的任何部分?你怀疑是什么问题,你做了什么来验证?

标签: python python-3.x matplotlib


【解决方案1】:

您将 x 和 y 值视为字符串,而您应该将它们解析为数字:

xs.append(float(x))
ys.append(float(y))

或者:

x, y = map(float, line.split(','))

结果:

【讨论】:

  • 我发现当x轴的类型为int或float时它可以正常工作。但是当 x 轴刻度与 int 和 char 混合时,是否有任何适当的方法来获得正确的顺序?例如。 NN3, NN10, NN15 .... 会按照 NN10, NN15, NN3.... /跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 2018-04-28
  • 2018-12-31
  • 1970-01-01
  • 2020-10-14
  • 2021-12-30
相关资源
最近更新 更多