Hide ticks in one of many axes from subplots in Matplotlib - python

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!

Related

Pyplot: change size of tick lines on axis

Consider this reproducable example:
import numpy as np
import matplotlib.pyplot as plt
labels = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(6, 3.5),dpi=300)
plt.subplots_adjust(wspace=0.025, hspace=0.2)
for ax in [a for b in axes for a in b]:
ax.imshow(np.random.randint(2, size=(22,42)))
ax.set_xticks([0,6,12,18,24,30,36,41])
ax.tick_params(axis='x', which='major', labelsize=3)
ax.set_yticks([])
ax.set_aspect('equal')
for ax in [item for sublist in axes for item in sublist][0::3]:
ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels,fontsize=3)
fig.savefig("example.png",bbox_inches='tight')
My issue is that even though I changed the tick font size, the lines of each tick remain the same. This looks ugly and wastes a lot of space, especially on the X axes. Any ideas how to get those lines smaller, thus that the xlabels are closer to the axis?
PS tight_layout() does not help.
Make
ax.tick_params(axis='x', which='major', labelsize=3, length=2)
and, right after,
ax.tick_params(axis='y', which='major', labelsize=3, length=2)
This will make the ticks smaller, but won't get the labels any closer to the chart.
PS: length=1 will make the ticks even smaller, obviously.
You could play with the width parameter:
ax.tick_params(axis='x', which='major', labelsize=3, width=0.1)
Instead of (line 4):
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(6, 3.5),dpi=300)
You can manipulate figsize. Example:
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(3, 2),dpi=300).
Lets's compare both outputs:
The numbers on axes are bigger than old one.

Move ticks and labels to the top of a pyplot figure

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.

How to set the same xtick for all subplots in python?

I'm creating subplots. I would like to set the same xtick for all subplots. I was able to set the xlabel in common for all subplots but I really don't know how to do for xticks. Any help?
fig, axs = plt.subplots(2, 2)
axs[0,0].plot(np.float64(datatime),np.float64(Tm),'--',color='black')
axs[0,0].set_ylim([min(Tm)-10,max(Tm)+10])
axs[0,0].set_ylabel('Temp. [°C]')
axs[0,1].plot(np.float64(datatime),np.float64(precip),'--',color='black')
axs[0,1].set_ylim([min(precip),max(precip)+20])
axs[0,1].set_ylabel('Rainfall [mm]')
axs[1,0].plot(np.float64(datatime),np.float64(PET),color='magenta')
axs[1,0].set_ylim([min(PET),max(PET)+10])
axs[1,0].set_ylabel('PET [mm]')
axs[1,1].plot(np.float64(datatime),np.float64(delta),color='cyan')
axs[1,1].set_ylim([min(delta),max(delta)+10])
axs[1,1].set_ylabel('P-PET [mm]')
plt.xticks(np.arange(min(datatime), max(datatime)+1, 12)) #here i define xticks
for ax in axs.flat:
ax.set(xlabel='Time [months]')
plt.show()
Within the for loop you can set the same ticks for each subplot
for ax in axs.flat:
ax.set(xlabel='Time [months]')
ax.set_xticks(np.arange(min(datatime), max(datatime)+1, 12))

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))

get the tick labels from a plot and use for another plot

I am trying to get the values of xticks from one plot and then use these values for another plot but set the new ticks as 10 to the power of the other plot's ticks. The following lines doesn't do the job I am aiming for
labels=[item for item in ax1.get_xticklabels()]
ax2.set_xticklabels(['$10^{{{:d}}}$'.format(int(i)) for i in labels])
I will appreciate for any suggestion.
What about sharing axes ? This will fix the same limits and number of ticks for ax1 and ax2 :
fig, ax = plt.subplots(1, 2, sharex=True)
ax1 = ax[0]
ax2 = ax[1]
Then your code will do the trick since you are sure that both subplots have the same xticks
labels = [item for item in ax2.get_xticklabels()]
ax2.set_xticklabels(['$10^{{{:d}}}$'.format(int(i)) for i in labels])

Categories

Resources