0

I want to change xlimits and xticks in one subplot of many subplots, but it only works for xticks.

I am plotting many plots, and almost all of them have the same x axis, in one figure and therefore have decided to use plt.subplots(sharex=True). For one plot I want different limits and ticks on my x axis. To do this, I remove this plot from the other sharex plots with ax.get_shared_x_axes().remove(ax).


import matplotlib.pyplot as plt
fig, axes = plt.subplots(4,10,sharey=True, sharex=True)

axes_flat = axes.flat

for i in range(0,33) :
   xs = axes_flat[i]
   xs.plot([0,1,2],[2,3,4])
   xs.set_xticks([0,2])
   xs.set_xlim([0,4])


#leave some room between normal plots and plots with different xlims:
axes_flat[34].axis('off')
axes_flat[35].axis('off')

# Remove this plot from the shared axes and change xlims and xticks:
axes_flat[36].get_shared_x_axes().remove(axes_flat[36])
axes_flat[36].set_xticks([0,1])
axes_flat[36].set_xlim([0,2])

axes_flat[38].axis('off')
axes_flat[39].axis('off')

plt.show()

enter image description here

This works as expected for the x limits but not for the xticks. Changing the ticks in one subplot overwrites all the other ticks, while the x limits are only changed in the subplot, which I wanted to. I do not understand why set_xticks and set_xlim would behave differently in this case. Is there a way to fix this, while still using plt.subplots(sharex=True) ?

P Keil
  • 91
  • 7
  • Try [this](https://stackoverflow.com/questions/54915124/how-to-unset-sharex-or-sharey-from-two-axes-in-matplotlib) – Sheldore Jun 27 '19 at 14:34
  • Thanks, I pretty much tried that, but it didn't work for me. You can acctually see in the example you gave that there is something strange going on with the ticks there too. – P Keil Jun 27 '19 at 14:53
  • While the sharing is reset, the ticker is still the same on all axes, so changing it on any axis, applies to all of them. – ImportanceOfBeingErnest Jun 27 '19 at 15:07
  • So how would I only change the ticker on one axis then? – P Keil Jun 27 '19 at 15:39
  • So I suppose your code comes from [this question](https://stackoverflow.com/q/54915124/4124317)? I gave a new answer to it and would suggest to close this as duplicate such that existing solution all stay in one place. – ImportanceOfBeingErnest Jun 28 '19 at 15:35
  • Yes my code partly came from there. Your new answer works for me, thanks. – P Keil Jul 01 '19 at 14:03

1 Answers1

-1

I don't know if there are a way to do this using plt.subplots(shared=True), but I did some similar, you could do like this:

ax1 = plt.subplot(121)
ax1.set_ylim(0, means_sd['mean'].max()+2)
ax1.bar(x=0, bottom=0, width=0.8, height=ref, color='gray')
ax1.set_xticks(list(range(len(data))))
ax1.set_xticklabels(s for s in labels)


ax2 = plt.subplot(122)
ax2.set_ylim(0, means_sd['mean'].max()+2)
ax2.bar(x=0, bottom=0, width=0.8, height=ref, color='gray')
ax2.set_xticks(list(range(len(data))))
ax2.set_xticklabels(s for s in labels)

I hope this helps.