Reputation: 61
I need all of my figures to have xlabel
, xticks
and xticklabels
on the top.
Since of that, I wrote a function to adjust plt.rcParams
which serves for initializing purpose.
However, it seems there is no such parameter to setup xlabel
to the top in advance. Here is a simplified showcase:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = True
plt.rcParams['xtick.labeltop'] = True
data = np.arange(9).reshape((3,3))
f,ax = plt.subplots()
ax.imshow(data)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
Currently the way I found to adjust it is putting ax.xaxis.set_label_position('top')
after calling ax.set_xlabel('x label')
.
I'm looking for a solution with two goals:
- It change the default x-label position so that every time
ax.set_xlabel()
is called, it shows up at the top.- This step could be executed before calling
ax.set_xlabel()
So I don't have to use ax.xaxis.set_label_position()
individually every time.
Extra:
As @r-beginners mentioned, the official reference did provide a example. But in the script they called is ax.set_title('xlabel top')
, which is different from ax.set_xlabel('x label')
. Note that a title is always on the top by default, regardless setting up plt.rcParams
or not. I assume they missed this issue by mistake.
Upvotes: 1
Views: 2226
Reputation: 25033
As far as I can tell, the position of the label of the x axis is hard-coded.
Let's look at the definition of the XAxis
class, the relevant file is .../matplotlib/axis.py
class XAxis(Axis):
...
def _get_label(self):
# x in axes coords, y in display coords (to be updated at draw
# time by _update_label_positions)
label = mtext.Text(x=0.5, y=0,
fontproperties=font_manager.FontProperties(
size=rcParams['axes.labelsize'],
weight=rcParams['axes.labelweight']),
color=rcParams['axes.labelcolor'],
verticalalignment='top',
horizontalalignment='center')
label.set_transform(mtransforms.blended_transform_factory(
self.axes.transAxes, mtransforms.IdentityTransform()))
self._set_artist_props(label)
self.label_position = 'bottom'
return label
...
As you can see, the vertical position of the label is hard-coded in the call to Text
, y=0
in display coordinates, to be updated at display time by _update_label_positions
and the label_position
is hard-coded to 'bottom'
.
Upvotes: 1
Reputation: 35155
There is an explanation in the official reference. This will help you deal with it.
import matplotlib.pyplot as plt
import numpy as np
# plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
# plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
x = np.arange(10)
fig, ax = plt.subplots()
ax.plot(x)
ax.set_xlabel('xlabel top') # Note title moves to make room for ticks
secax = ax.secondary_xaxis('top')
secax.set_xlabel('new label top')
plt.show()
Upvotes: 0