python - 使用 matplotlib 库绘制列表(不按顺序)时如何纠正 y 间隔?

标签 python matplotlib text-files graphing

绘制图表时 y 值未按顺序排列

COLst3 是不按顺序排列的数字列表。示例 COLst3 列表:

['312', '313', '313', '312', '311', '313', '311', '311', '311', '310']

x 轴是时间,y 轴是 COLst3。 创建的空列表是为了创建x值点。

我需要帮助以一致的 y 间隔正确绘制值。

import time
import matplotlib.pyplot as plt
import numpy as np

def COfunction():
    x=0
    z=1
    y=60 #change y according to the estimated number of CO values recorded
    COLst = []
    COLst3 = []
    empty = []

    while x < y: 
        open_file=open(r'C:\Users\MindStorm\Desktop\capture.txt','r')
        file_lines=open_file.readlines()
        file = file_lines[x].strip()  # First Line
        COLst = file.split()
        COLst2 = COLst.pop(1)
        COLst3.append(COLst2)
        empty.append(z)
        x += 6
        z += 1

    #plots using matplotlib library
    plt.title('CO Displacement value Graph')
    plt.xlabel('Time(seconds)')
    plt.ylabel('Sensor values(volts)')
    plt.plot(empty, COLst3)
    plt.show()

#main functions
COfunction()

代码运行成功,但我需要正确的 y 值间隔来绘制两个列表。

Matplotlib 版本:2.2.3

Result

最佳答案

问题是您的值是字符串,这就是它们乱序的原因。分别使用 intfloat 将它们转换为整数或浮点类型。

COLst3 = ['312', '313', '313', '312', '311', '313', '311', '311', '311', '310']
COLst3 = list(map(int, COLst3)) # <--- Convert strings to integer

empty = range(len(COLst3))

plt.title('CO Displacement value Graph')
plt.xlabel('Time(seconds)')
plt.ylabel('Sensor values(volts)')
plt.plot(empty, COLst3)
plt.yticks(range(min(COLst3), max(COLst3)+1)) # <--- To show integer tick labels
plt.show()

enter image description here

关于python - 使用 matplotlib 库绘制列表(不按顺序)时如何纠正 y 间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585476/

相关文章:

python - 将列表的字符串开头与白名单进行比较

PHP 按数字排序文本文件 (.txt)

php - 对 HTML 表格中的文本文件中的数据进行排序

python - 使用 Selenium 的谷歌帐户登录自动化导致错误

Python - 直接从硬盘读取

python - 如何更改烛台图表中阴影垂直线的颜色?

python - 图像像素上的 matplotlib 标记/掩码

java - 如何在java中对文本文件进行排序和排列以对行进行分组

python - Pandas : "ValueError: could not convert string to float: "(空字符串)

python - scipy.polyfit(x, y, 100) 将是 100 阶多项式,但 matplotlib.pyplot.legend 显示 53?