2016-10-22 44 views
0

我想要顯示所有13 x ticks,但圖表只顯示其中7個具有兩個區間。控制pyplot中的x tick的數量

plt.locator_params(axis='x',nbins=13) 

爲什麼不上面的代碼工作?

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 
import matplotlib.dates as dates 

y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813] 

times = pd.date_range('2015-02-25', periods=13) 
fig, ax = plt.subplots(1) 
fig.autofmt_xdate() 

xfmt = dates.DateFormatter('%d-%m-%y') 
ax.xaxis.set_major_formatter(xfmt) 

plt.locator_params(axis='x',nbins=13) 

ax.plot_date(times.to_pydatetime(), y, 'v-') 
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1), 
              interval=1)) 
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a')) 
ax.xaxis.grid(True, which="minor") 
ax.yaxis.grid() 
plt.tight_layout() 
plt.show() 

enter image description here

+0

如果答案解決了您的問題[接受它](http://i.stack.imgur.com/QpogP.png),以便其他人知道它會在第一瞥中工作。 – Yugi

回答

1

警告應該給你一些線索,爲什麼發生這種情況:

UserWarning: 'set_params()' not defined for locator of type <class 'pandas.tseries.converter.PandasAutoDateLocator'> 
    str(type(self))) 

使用plt.xticks(times.to_pydatetime())代替:

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 
import matplotlib.dates as dates 

y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813] 

times = pd.date_range('2015-02-25', periods=13) 
fig, ax = plt.subplots(1) 
fig.autofmt_xdate() 

xfmt = dates.DateFormatter('%d-%m-%y') 
ax.xaxis.set_major_formatter(xfmt) 


ax.plot_date(times.to_pydatetime(), y, 'v-') 
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1), 
              interval=1)) 
plt.xticks(times.to_pydatetime()) 
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a')) 
ax.xaxis.grid(True, which="minor") 
ax.yaxis.grid() 
plt.tight_layout() 
plt.show() 

enter image description here