I'm having trouble changing the tick label properties on a plot with twin axes. I want the text to be small and in a different font than the default. I found a way that worked fine until I tried using twiny(). The second axes doesn't respond to the tick-formatting instructions, as you can see on the figure. Am I missing something crucial or is there a bug in matplotlib?
Ubuntu 12.04, Python 2.7.3, matplotlib 1.1.1rc
#!/usr/bin/env python
# coding: utf-8
from matplotlib import pyplot as p
from numpy import sin, cos, arange
x = arange(0, 10, .01)
for plotnum in range(1,5):
p.subplot(2, 2, plotnum)
ax1 = p.gca()
p.plot(sin(x),x)
ax2 = p.twiny()
p.plot(cos(x)+plotnum,x, 'g--')
# Set size all tick labels
# Works for first axes (lower x-ticks) and can also change font
for tickset in [ax1.xaxis.get_major_ticks()]:
[(tick.label.set_fontsize(plotnum*4), tick.label.set_fontname('ubuntu mono')) for tick in tickset]
# Does not work for second axes (upper x-ticks)
for tickset in [ax2.xaxis.get_major_ticks()]:
[(tick.label.set_fontsize(plotnum*2), tick.label.set_fontname('ubuntu mono')) for tick in tickset]
# This works, but doesn't allow changing font
#ax2.tick_params(axis='both', which='major', labelsize=plotnum*2)
Here is an image:
Edit: fixed incorrect indenting of tick-changing lines
Edit: Inserted image (Thriveth)
If we want to change the font size of the axis labels, we can use the parameter “fontsize” and set it your desired number.
Ticks can have two labels (label1
and label2
), according to the Tick class documentation:
The label
attribute always refers to label1
.
You can fix your script by changing the ax2 lines to:
for tickset in [ax2.xaxis.get_major_ticks()]:
[(tick.label2.set_fontsize(plotnum*2), tick.label2.set_fontname('ubuntu mono'))
The get_majorticklabels
functions will work out if you 'll need label1
or label2
and simplifies your script:
from matplotlib import pyplot as p
from numpy import sin, cos, arange
x = arange(0, 10, .01)
for plotnum in range(1,5):
p.subplot(2, 2, plotnum)
ax1 = p.gca()
p.plot(sin(x),x)
ax2 = p.twiny()
p.plot(cos(x)+plotnum,x, 'g--')
for label in ax1.xaxis.get_majorticklabels():
label.set_fontsize(plotnum * 4)
label.set_fontname('courier')
for label in ax2.xaxis.get_majorticklabels():
label.set_fontsize(plotnum * 4)
label.set_fontname('verdana')
Note, I put the label change routines in the loop!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With