Bob Markley
Bob Markley

Reputation: 45

Matplotlib tick alignment

I am trying to have twin tick marks on the top and bottom of my plot. Unfortunately, for some reason these ticks are just not aligning in this plot:

http://puu.sh/cE2Ez/f270ab625e.png

As per my code:

plt.xlim([0, ncols])
plt.ylim([0, nrows])
plt.gca().invert_yaxis()
plt.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off')

plt.tight_layout()
  #ticks
rect.set_yticks([0, 64, 128, 192, 256])
rect.get_yaxis().set_major_formatter(ticker.ScalarFormatter())

rect.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off',     labelsize=6)
xaxisbot = [int(args.UTC_time) + 11 * 110 * x for x in range(1833 / 110 + 1)]
xaxistop = [x2 * 110 for x2 in range(1833/110+1)]
plt.xticks(xaxistop, xaxisbot)

rect2 = rect.twiny()
rect2.tick_params(axis='both', which='both', left='off', right='off', top='off', bottom='off', labelsize=6)
rect2.set_xticks(xaxistop)
rect2.xaxis.tick_top()

These ticks don't seem to be matching up. Is there a better way for me to align them, especially when I'm using labels?

On a secondary note, when I try to create a bunch of these plots in a loop, these ticks just paste over each other instead of deleting and clearing. However, when I use cla(), none of my plots generate. Is there a way to get around that?

Upvotes: 0

Views: 908

Answers (1)

Greg
Greg

Reputation: 12234

Your code is very complex, try to strip away anything that is irrelevant to the problem and present a minimal working example. In particular we can't run your code since rect and args are undefined!

From what I can gather the issue is arising because after this piece of code you plot the data on either rect or rect2. I assume these are axis instances. If so then the following reproduces

import matplotlib.pyplot as plt
import numpy as np

ax1 = plt.subplot(111)

xaxisbot = [11 * 110 * x for x in range(1833 / 110 + 1)]
xaxistop = [x2 * 110 for x2 in range(1833/110+1)]


ax1.tick_params(labelsize=6)
ax1.set_xticks(xaxisbot)

ax2 = ax1.twiny()
ax2.tick_params(labelsize=6)
ax2.set_xticks(xaxistop)
ax2.xaxis.tick_top()

# Add data to ax2
ax2.plot(range(1500), range(1500))

ax.grid()
plt.show()

enter image description here

So to fix this you simply need to manually set the limits. For example adding:

ax1.set_xlim(xaxisbot[0], xaxisbot[-1])
ax2.set_xlim(xaxistop[0], xaxistop[-1])

or, in terms of the code you have given

rect.set_xlim(xaxisbot[0], xaxisbot[-1])
rect2.set_xlim(xaxistop[0], xaxistop[-1])

enter image description here

PS: You should have a look at the line in your plt.xticks(xaxistop, xaxisbot) is this really what you mean? It didn't make sense to me but it has some purpose..

Upvotes: 1

Related Questions