'How to ensure that the labels of two axes do not overlap?

I have some questions about labels of axs.

Firstly,I have 2 subplots which can be seen below. As you can see, labels of first ax are overlapping with the second ax. I want to seperate them so that labels can be seen clearly.

Secondly, As you can see in the output example below, only some labels are displayed. I want them all to appear. As a result of my research, I could not find such a method. How can I solve it?

Additionally, If I want it to draw only after the date I want, what command should I enter? In other words, The data plotted starts from 2015. However, I only want to see it from 2017. What should I do?

Thanks for your answers.



##DRAWING
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

df2['NUMUNE']=pd.to_datetime(df2['NUMUNE'].astype(str), format='%Y/%m/%d')

fig, (ax1, ax2) = plt.subplots(2, figsize=(15,8))

fig.suptitle('{} Kuyusu Verileri'.format(e1_string))

ax1.plot(df2['NUMUNE'], df2['Su Seviyesi (m)'], label= 'Su Seviyesi (m)')

ax1.plot(df2['NUMUNE'], df2['KUYU KOTU (m)'], label= 'KUYU KOTU (m)')

ax1.get_ygridlines()

ax1.get_yticklines(minor=False)

ax1.legend(loc="upper right")

ax1.grid()

ax2.plot(df2['NUMUNE'], df2['NaHCO3'], label = '% NaHCO3' )

ax2.plot(df2['NUMUNE'], df2['Na2CO3'], label = '% Na2CO3' )

ax2.plot(df2['NUMUNE'], df2['TA'], label = '% TA' )

ax2.get_ygridlines()

ax2.get_yticklines(minor=False)

ax2.legend(loc="upper right")

ax2.grid()

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# Rotates and right-aligns the x labels so they don't crowd each other.
for label in ax1.get_xticklabels(which='major'):
    label.set(rotation=90, horizontalalignment='right')
    
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# Rotates and right-aligns the x labels so they don't crowd each other.
for label in ax2.get_xticklabels(which='major'):
    label.set(rotation=90, horizontalalignment='right')



plt.savefig('kuyuseviyesi.jpg')

output: Output



Solution 1:[1]

These lines of code will fix your plot

plt.tight_layout(pad=2)
ax2.tick_params(
    axis='x', 
    which='both',
    bottom=False,
    top=False, 
    labelbottom=False)

ax1.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(ax1.get_xticks()[5:]))

The tight_layout() method helps add some space in between the plots, tick_params() will get rid of the xticks of the bottom plot and lastly you can chose where the xticks will begin with the FixedLocator() method. You need to pass a list with the xticks you already have on your plot so it understands it, you can pass your own or ax.get_xticks() will get those for you, in my example, I sliced through the list just for clarity.enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1