Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only first and last ticks label of x-axis plot

I'm parsing a log file and creating a plot.

I don't need all labels on X axis. I want to display only a first one and a last one or a few of them with particular step let's say every 100.

How I can do this? I can display only first one or only last one but not both together.

My code:

import numpy as np
import pylab as pl
import matplotlib.pyplot as plt

with open('file.log') as f:
    lines = f.readlines()
    x = [int(line.split(',')[0]) for line in lines]
    my_xticks = [line.split(',')[1] for line in lines]
    y = [int(line.split(',')[2]) for line in lines]
    z = [int(line.split(',')[3]) for line in lines]

plt.xticks(x, my_xticks[0], visible=True, rotation="horizontal")
plt.xticks(x, my_xticks[-1], visible=True, rotation="horizontal")

plt.plot (x,z)
plt.plot (x,z)
plt.plot(x, y)


plt.show()

Thank you!

like image 876
tyon Avatar asked Sep 06 '25 20:09

tyon


1 Answers

with x-ticks, you can provide a list. So you can do:

plt.xticks([my_xticks[0], my_xticks[-1]], visible=True, rotation="horizontal")

Incidentally, you can get the original ticks using:

my_xticks = ax.get_xticks()

where ax is your your Axes instance. You can even supply your own values:

plt.xticks(
          [my_xticks[0], my_xticks[-1]], 
          ['{:.2}'.format(my_xticks[0]), '{:.2}'.format(my_xticks[-1])]
           visible=True, rotation="horizontal")

etc. You can see how easily this can be generalized ...

Just remember that the tick labels refer to specific Axes within the figure. So ideally you should do:

`ax.set_xticks(..)`
like image 182
ssm Avatar answered Sep 09 '25 23:09

ssm