2016-03-09 90 views
2

之间违规行为在时间序列上的标签在创建条形图,并通过熊猫我已经遇到了一些不一致的行为使用matplotlib线图。例如:熊猫matplotlib绘制,柱状图和线形图

import matplotlib.pyplot as plt 
import pandas as pd 
from pandas_datareader import data 

test_df = data.get_data_yahoo('AAPL', start='2015-10-01') 
test_df['Adj Close'].plot() 

地块如预期有合理的X轴标签:

enter image description here

但是,如果你再尝试绘图来自同一数据框的东西为条形图:

test_df['Volume'].plot(kind='bar') 

enter image description here

的x轴刻度标签不再自动显示。

是大熊猫/ matplotlib的这种预期的行为?那么如何能够轻松地纠正条形图上的x轴刻度标签与上面线形图中的标签类似?

回答

3

你可以告诉matplotlib显示每N个标签:

# show every Nth label 
locs, labels = plt.xticks() 
N = 10 
plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d')) 

import matplotlib.pyplot as plt 
import pandas as pd 
from pandas_datareader import data 

test_df = data.get_data_yahoo('AAPL', start='2015-10-01') 
fig, ax = plt.subplots(nrows=2) 
test_df['Adj Close'].plot(ax=ax[0]) 
test_df['Volume'].plot(kind='bar', ax=ax[1]) 

# show every Nth label 
locs, labels = plt.xticks() 
N = 10 
plt.xticks(locs[::N], test_df.index[::N].strftime('%Y-%m-%d')) 

# autorotate the xlabels 
fig.autofmt_xdate() 
plt.show() 

产量 enter image description here


另一种选择是matplotlib直接使用:

import matplotlib.pyplot as plt 
import pandas as pd 
from pandas_datareader import data 
import matplotlib.dates as mdates 

df = data.get_data_yahoo('AAPL', start='2015-10-01') 
fig, ax = plt.subplots(nrows=2, sharex=True) 

ax[0].plot(df.index, df['Adj Close']) 
ax[0].set_ylabel('price per share') 

ax[1].bar(df.index, df['Volume']/10**6) 
ax[1].xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1)) 
xfmt = mdates.DateFormatter('%B %d, %Y') 
ax[1].xaxis.set_major_formatter(xfmt) 
ax[1].set_ylabel('Volume (millions)') 

# autorotate the xlabels 
fig.autofmt_xdate() 
plt.show() 

enter image description here

+0

感谢,除了会是可能的,只是情节一个月,一年x轴上(如十月,2015年),你会怎么做y轴人类可读? – BML91

+1

你想如何看y标签? – unutbu

+0

实际上可能是相同的,只是没有1e8和y轴标签(即卷(百万))的回报规模? – BML91