pythonmatplotlib

matplotlib x axis not as expected


I want the x-axis labels to be exactly as in the file, but it's converting them. Also, I don't want the thick black line above the labels. And, I'd like the plot to extend fully to both sides of the area without the empty spaces on the left and right.

plot: enter image description here

python script:

#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np

a,b = np.genfromtxt("test01.txt", usecols=(0,1), unpack=True, delimiter="\t", dtype='str')
y = list(map(float, b))

plt.figure(figsize=(9, 5)) 
plt.plot(a, y, linewidth=0.7)
xticks = plt.xticks()[0]
xtick_labels = ["" if i % 100 != 0 else x for i, x in enumerate(xticks)]
plt.xticks(xticks, xtick_labels, fontsize=8)
plt.xticks(rotation=90)
plt.yticks(np.arange(100, 185, 5))
plt.ylim(110, 185)
plt.xlabel("Time")
plt.ylabel("Temp in F")
plt.show()

sample data from the file:

00:00:02    170.9
00:00:03    171.7
00:00:04    171.9
00:00:04    171.8
00:00:05    171.4
00:00:06    170.9
00:00:07    170.1
00:00:08    169.4
00:00:09    168.5
00:00:10    167.6

Solution

  • enter image description here

    If what you want to do is to use the strings in the file as the labels of the x-ticks, you have to proceed carefully:

    1. save the (too many) positions of the x-ticks and rhe corresponding labels in two lists, positions and texts
    2. remove the x-ticks completely
    3. construct two lists p and t to store the positions and the texts that we want on the final drawing
    4. using p and t, place the selected pairs on the final drawing

    Eventually, rotate the labels and prescribe a tight layout, otherwise the labels are truncated.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = '''\
    00:00:02    170.9
    00:00:03    171.7
    00:00:04    171.9
    00:00:04    171.8
    00:00:05    171.4
    00:00:06    170.9
    00:00:07    170.1
    00:00:08    169.4
    00:00:09    168.5
    00:00:10    167.6'''
    
    x, y = zip(*[line.split() for line in data.split('\n')])
    y = [float(s) for s in y]
    
    plt.plot(x, y)
    
    # this is the interesting part
    # save the x ticks
    positions, texts = plt.xticks()
    # remove the x ticks
    plt.xticks([],[])
    # select the ticks we want from the saved ones
    p, t = [], []
    for k in range(len(positions)):
        if not k%3:
            p.append(positions[k])
            t.append(texts[k])
    # set the ticks according to our preference
    plt.xticks(p, t)
    # end of the interesting part
    plt.xticks(rotation=+90)
    plt.tight_layout()
    plt.show()