Hello!
First of all, there are several different ways to solve these customization problems. Below is a way I usually use and seems more readable.
In this case, I have defined a axis
where all Plots and customizations will be set:
# Definição do axis
fig, ax = plt.subplots(1,1)
# Note que agora é necessário definir o axis que cada plot será exibido
tesla['Open'].plot(ax = ax, label = "Tesla", figsize = (16,8), title = "Open Price")
gm['Open'].plot(ax = ax, label = "GM")
ford['Open'].plot(ax = ax, label = "Ford")
From the image of your question, it seems to me xticks
has been separated into 6 month intervals. Whereas the indexes of all Dataframes are the same, it is necessary to define the position where each xtick
will appear and then format it to appear 2016-07
, for example.
# Cria um vetor com as datas a cada 6 meses
# O parâmetro freq pode receber diversas frequências diferentes (Y, m, d, ...)
positions = pd.date_range(tesla.index[0], tesla.index[-1], freq='6m')
# Formata os labels
labels = positions.strftime('%Y-%m')
Now set the dates formatted on the abscissa axis
# Remove localizadores desnecessários no eixo x
ax.xaxis.set_minor_locator(plt.NullLocator())
# Seta a posição das datas
ax.set_xticks(positions[1:])
# Seta os labels nas devidas posições
ax.set_xticklabels(labels[1:])
To tilt the Abels, simply add a rotation to the xticks
with the command plt.xticks(rotation = angle)
, where the angle
is the angle of rotation in degrees of the xticks relative to the axis of the abscissas.
plt.xticks(rotation = 30)
Finally, we set the graph to be adjusted to the image
plt.autoscale(axis = 'x', tight=True)
Complete code:
fig, ax = plt.subplots(1,1)
tesla['Open'].plot(ax = ax, label = "Tesla", figsize = (16,8), title = "Open Price")
gm['Open'].plot(ax = ax, label = "GM")
ford['Open'].plot(ax = ax, label = "Ford")
positions = pd.date_range(tesla.index[0], tesla.index[-1], freq='6m')
labels = positions.strftime('%Y-%m')
ax.xaxis.set_minor_locator(plt.NullLocator())
ax.set_xticks(positions[1:])
ax.set_xticklabels(labels[1:])
plt.xticks(rotation = 30)
plt.legend()
plt.autoscale(axis = 'x', tight=True)
References:
https://stackoverflow.com/questions/44078409/matplotlib-semi-log-plot-minor-tick-marks-are-gone-when-range-is-large
https://scentellegher.github.io/programming/2017/05/24/pandas-bar-plot-with-formatted-dates.html