Move ticks and labels to the top of a pyplot figure - python

As per this question, moving the xticks and labels of an AxesSubplot object can be done with ax.xaxis.tick_top(). However, I cannot get this to work with multiple axes inside a figure.
Essentially, I want to move the xticks to the very top of the figure (only displayed at the top for the subplots in the first row).
Here's a silly example of what I'm trying to do:
fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
fig.set_figheight(5)
fig.set_figwidth(10)
for ax in axs.flatten():
ax.xaxis.tick_top()
plt.show()
Which shows
My desired result is this same figure but with the xticks and xticklabels at the top of the two plots in the first row.

Credits to #BigBen for the sharex comment. It is indeed what's preventing tick_top to work.
To get your results, you can combine using tick_top for the two top plots and use tick_params for the bottom two:
fig, axs = plt.subplots(2, 2, sharex=False) # Do not share xaxis
for ax in axs.flatten()[0:2]:
ax.xaxis.tick_top()
for ax in axs.flatten()[2:]:
ax.tick_params(axis='x',which='both',labelbottom=False)
See a live implementation here.

Related

how to make Y-label of subplots to appear only once?

I have a simple problem i need to solve, here is the example
import matplotlib.pyplot as plt
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(6, 6))
for axs in ax.flat:
axs.set(ylabel='AUC')
this is the output
I want Y-label(AUC) to appear only once(be shared) at the first subplot, and other values should remain. This is the desired output
How to solve this? Please I need your help
Since you're setting your labels in a loop, you're labeling all the axes in your subplots accordingly. What you need is to only label the first cell in your subplot row.
So this:
for axs in ax.flat:
axs.set(ylabel='AUC')
changes to:
ax[0].set_ylabel("AUC")
I also recommend you to share the axis between your multiple subplots, since all the yticks are making your plot a little less readable than ideal. You can change it as below:
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(6, 6), sharex=True, sharey=True,)
The resulting image will be:

Removing overlapping x-axis labels in pyplot

I'm new to python and attempting to chart some time series data. I'm using pyplot to create 3 stacked line charts which have the same x-axis (dates), but a different scale for the y-axes. However, each y-axis, as well as the x-axis for the bottom chart, have overlapping labels. There are labels generated from 0 to 1, as well as axis labels from my data set. How do I turn 'off' the auto-generated 0 to 1 labels on the y-axes and the bottom x-axis?
fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))
ax = fig.add_subplot(3,1,1)
plt.plot(df1['date'], df1['value'])
ax2 = fig.add_subplot(3,1,2)
plt.plot(df2['date'], df2['value'])
ax3 = fig.add_subplot(3,1,3)
plt.plot(df3['date'], df3['value'])
plt.show()
You can see the issue in the below picture. Any help is greatly appreciated!
You have already created subplots with all the axes in the initial assignment
fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))
therefore the following assignements of
ax = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)
are not only unnecessary, but they seem to overlap the already created subplots (if you change it to add_subplot(2,1,1) you will notice it just starts dividing figure again and overlaying axes on top of each other).
What you want to do, is access the axes created in plt.subplots() call:
fig, ax = plt.subplots(3,1,sharex='all', squeeze=False, figsize=(12,8))
ax[0].plot(df1['date'], df1['value'])
ax[1].plot(df2['date'], df2['value'])
ax[2].plot(df3['date'], df3['value'])
plt.show()
Simulated Output:
Data from seaborn tips dataset

How can axes be despined in Matplotlib?

I am trying to make the below grid of plots a little bit cleaner. I don't want the tick marks on the left side and the bottom to overlap. I have tried to despine the axes by trying the below code, but it doesn't seem to work. Anyone have any suggestions?
fig, ax = plt.subplots(figsize=(15,10))
cols = ['x6', 'x7', 'x16', 'x17']
subset = df[cols]
normed_df = (subset-subset.min())/(subset.max()-subset.min())
style.use('seaborn-darkgrid')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
for sp in range(4):
ax = fig.add_subplot(2,2, sp+1)
ax.hist(normed_df[cols[sp]], density=True)
normed_df[cols[sp]].plot.kde(ax=ax)
ax.tick_params(bottom="off", top="off", left="off", right="off")
After running the above code, I am getting the following plots, however, the ticks are still overlapping.
either do what #Arne suggested:
fig, ax = plt.subplots(rows, cols) #makes a grid of subplots
or make your first two lines this:
fig, ax = plt.subplots(figsize=(15,10))
ax.axis('off')
this will remove the axis around the entire subplot before adding your additional subplots
When you call plt.subplots() without specifying a grid, it creates those axes across the whole figure whose tick marks and labels interfere with your subplot tick labels in the final plot. So change your first line of code to this:
fig, ax = plt.subplots(2, 2, figsize=(15,10))

Hide ticks in one of many axes from subplots in Matplotlib

In the following plot
f, (ax1,ax2) = plt.subplots(2,1, figsize=(7,8), sharex=True,
gridspec_kw={'height_ratios':[3,1],'hspace':0.05})
I would like to hide ax1.xticks but show ax2.xticks.
With ax1.set_xticks([]) I end up hiding ax1 and ax2 ticks.
found it!
ax1.tick_params(bottom='off')
do the job!

Matplotlib: reorder subplots

Say that I have a figure fig which contains two subplots as in the example from the documentation:
I can obtain the two axes (the left one being ax1 and the right one ax2) by just doing:
ax1, ax2 = fig.axes
Now, is it possible to rearrange the subplots? In this example, to swap them?
Sure, as long as you're not going to use subplots_adjust (and therefore tight_layout) after you reposition them (you can use it safely before).
Basically, just do something like:
import matplotlib.pyplot as plt
# Create something similar to your pickled figure......
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot(range(10), 'r^-')
ax1.set(title='Originally on the left')
ax2.plot(range(10), 'gs-')
ax2.set(title='Originally on the right')
# Now we'll swap their positions after they've been created.
pos1 = ax1.get_position()
ax1.set_position(ax2.get_position())
ax2.set_position(pos1)
plt.show()

Categories

Resources