Home > Back-end >  Problems with range on x-axis when using mdates
Problems with range on x-axis when using mdates

Time:04-22

I'm having trouble adjusting the x-axis range on the figure below. The data is monthly, starting from 1995-01-31 and ends at 2022-03-31, and I want only to display years. This I solved with mdates. So far so good.

However, I don't want to display 1994 and 2023. I want to set the xlim to 1995 and 2022. How can I do this after I used mdates?

(I don't want to use set_visible(False), I want the the line to start as close to the y-axis as possible.)

Figure

fig, ax = plt.subplots(figsize=(15,6))
    
plt.grid(True, which='major', axis='y', color='#000000', alpha=0.2, linestyle='-')

plt.title('TITLE\nTEXT TEXT\n', fontdict={'fontsize': '20', 
                        'fontname':'Arial'})

plt.plot(df['Perc'],linewidth=4, color=blå)
ax.xaxis.set_major_locator(mdates.YearLocator())
plt.xticks(rotation=30)

#x_ticks = ax.xaxis.get_major_ticks() # Tried to get the x-ticks like this and use them in xlim. 
#plt.xlim(x_ticks[1].label,x_ticks[-2].label)
#plt.xlim(?,?)

plt.annotate('Source: XXXXX', 
             xycoords='figure fraction', fontsize=14, color='#000000', xy=(0.4, .024))

ax.annotate('Percent', 
             xycoords='figure fraction', fontsize=14, color='#000000', xy=(0.065, .9))

plt.rc('xtick', labelsize=14)    
plt.rc('ytick', labelsize=14)  

plt.show()


CodePudding user response:

The sample data is a graph of FORD stock prices for a maximum period of one month. to correct the automatic addition of start and end margins on the x-axis, the x-axis scale used in the graph can be obtained and the start and end margins can be changed. Finally, since the writing style is a mixture of plt and ax, we have aligned it with ax as the basis.

import yfinance as yf
df = yf.download("FORD", inverbal='1mo', period='max')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots(figsize=(15,6))
    
ax.grid(True, which='major', axis='y', color='#000000', alpha=0.2, linestyle='-')

ax.set_title('TITLE\nTEXT TEXT\n', fontdict={'fontsize': '20', 'fontname':'Arial'})

ax.plot(df['Close'], linewidth=4, color='black')
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.tick_params(axis='x', labelrotation=45)
new_xticks = ax.get_xticks()
#print(new_xticks)
ax.set_xlim(new_xticks[2], new_xticks[-2])

ax.annotate('Source: XXXXX', xycoords='figure fraction', fontsize=14, color='#000000', xy=(0.4, .024))
ax.annotate('Percent', xycoords='figure fraction', fontsize=14, color='#000000', xy=(0.065, .9))

plt.rc('xtick', labelsize=14)    
plt.rc('ytick', labelsize=14)  

plt.show()

enter image description here

  • Related