janicewww
janicewww

Reputation: 333

Configurate x-axis by MaxNLocator Seaborn

I want to use MaxNLocator function to change the x-axis ticks because it is too crowded. However, it doesn't works. May I know what is the problem?

from pandas_datareader import data
import datetime

tickers = 'MP'

dateToday = datetime.datetime.today().strftime("%Y-%m-%d")

# Only get the adjusted close.
tickers_data = data.DataReader(tickers,
                       start='', 
                       end=dateToday, 
                       data_source='yahoo')[["Adj Close", "Volume"]][-250:]

import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
# sns.set_style("darkgrid")

plt.figure(figsize=(12,6))

sns.barplot(x=tickers_data.index.strftime('%d/%-m'), y=tickers_data['Volume'], color='#73a9d1')
plt.MaxNLocator(10)
plt.xticks(rotation = 90)
plt.ticklabel_format(style='plain', axis='y')
plt.ylabel('Volume')
plt.title(tickers)

axes2=plt.twinx()
axes2.plot(tickers_data.index.strftime('%d/%-m'), tickers_data['Adj Close'], color='b', linewidth=0.5)
axes2.set_ylabel('Price')

output: enter image description here

Another plot:

plt.figure(figsize=(12,6))

ax = sns.barplot(x=returns.index.strftime('%d/%-m'), y=returns['Adj Close'], color='#73a9d1')

plt.xticks(rotation = 90)
ax.xaxis.set_major_locator(tic.MaxNLocator(nbins=60))
plt.title('returns')

Upvotes: 2

Views: 614

Answers (1)

Zalak Bhalani
Zalak Bhalani

Reputation: 1144

Import matplotlib.ticker and Use it in axes2

from pandas_datareader import data
import datetime

tickers = 'MP'

dateToday = datetime.datetime.today().strftime("%Y-%m-%d")

# Only get the adjusted close.
tickers_data = data.DataReader(tickers,
                       start='', 
                       end=dateToday, 
                       data_source='yahoo')[["Adj Close", "Volume"]][-250:]

import matplotlib.ticker as tic # Imported Ticker
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
# sns.set_style("darkgrid")

plt.figure(figsize=(12,6))

sns.barplot(x=tickers_data.index.strftime('%d/%-m'), y=tickers_data['Volume'], color='#73a9d1')
plt.xticks(rotation = 90)
plt.ticklabel_format(style='plain', axis='y')
plt.ylabel('Volume')
plt.title(tickers)

axes2=plt.twinx()
axes2.plot(tickers_data.index.strftime('%d/%-m'), tickers_data['Adj Close'], color='b', linewidth=0.5)
axes2.xaxis.set_major_locator(tic.MaxNLocator(nbins=10)) #Added Here
axes2.set_ylabel('Price')

Upvotes: 2

Related Questions