首页 > 解决方案 > 如何在 y 轴上获得正确的顺序(matplotlob(P 2.7)正确

问题描述

我想知道为什么y轴的顺序是随机的(见截图)。我正在绘制带有值对的文本文件中的 x 和 y 值,并且希望 y 轴从最小值开始并以最大值结束。在我的例子中,y 轴图的中间有最小的数字 (3)。我该如何纠正这个错误?

txt 文件:

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

代码:

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('example.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)  # 1000 ms = 1 sec (updating)
plt.show()

在此处输入图像描述


我发现编辑以下两行代码有帮助!!!

之前: xs.append(x) ys.append(y)

之后: xs.append(float(x)) ys.append(float(y))

在此处输入图像描述

标签: pythonmatplotlib

解决方案


您在行上指定了 FiveThirtyEight 样式

style.use('fivethirtyeight') 

只需将其删除即可使用正常的绘图样式。


推荐阅读