How to set the xticks equal to that figure

Asked

Viewed 819 times

1

I’m taking a course in Python geared towards finance. Then in an exercise you are asked to plot a graph using Dataframes. So far so good, I managed to do everything right, however my xticks do not match those of the result!

I have to get basically this:inserir a descrição da imagem aqui

But I’m getting it here: inserir a descrição da imagem aqui

Would anyone know how to get me the same xticks as the citizen?

Note: These are time series in Pandas that must be plotted ford, Esla and gm are Dataframes and I am filling the 'Open' column of this dataframe. The indices of the Dataframes are all the same, dates 2012-01-01 until 2017-01-01.

Obs2.: The code used by prof. was the following:

tesla['Open'].plot(label='Tesla',figsize=(16,8),title='Open Price')
gm['Open'].plot(label='GM')
ford['Open'].plot(label='Ford')
plt.legend()

1 answer

0


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)

inserir a descrição da imagem aqui

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.