Search code examples
pythonmatplotlibtext-filesgraphing

How do you correct the y-intervals when graphing a list(not in order) using matplotlib library?


The y values are not in order when graphed

The COLst3 is a list of numbers that are not in order. A sample COLst3 list:

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

The x-axis is time, and the y-axis is the COLst3. the empty list created is to create the x value points.

I need help with graphing the values correctly on a consistent y interval.

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()

The code runs succesfully, but I need correct y value intervals to graph both lists.

Matplotlib version: 2.2.3

Result


Solution

  • The problem is that your values are strings that's why they are out of order. Convert them to either integer or float type using int or float, respectively.

    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