2017-10-15 43 views
0

我目前有一個數據框,其索引是1990年至2014年(25行)的年份。我希望我的情節能夠顯示所有年份的X軸。我正在使用add_subplot,因爲我計劃在這個圖中有4個圖(所有圖都具有相同的X軸)。將Xticks頻率設置爲數據幀索引

要創建數據框:

import pandas as pd 
import numpy as np 

index = np.arange(1990,2015,1) 
columns = ['Total Population','Urban Population'] 

pop_plot = pd.DataFrame(index=index, columns=columns) 
pop_plot = df_.fillna(0) 

pop_plot['Total Population'] = np.arange(150,175,1) 
pop_plot['Urban Population'] = np.arange(50,125,3) 

,我目前擁有的代碼:

fig = plt.figure(figsize=(10,5)) 
ax1 = fig.add_subplot(2,2,1, xticklabels=pop_plot.index) 
plt.subplot(2, 2, 1) 

plt.plot(pop_plot) 
legend = plt.legend(pop_plot, bbox_to_anchor=(0.1, 1, 0.8, .45), loc=3, ncol=1, mode='expand') 
legend.get_frame().set_alpha(0) 

ax1.set_xticks(range(len(pop_plot.index))) 

這是陰謀,我得到:

Plot with ax1.set_xticks

當我發表評論set_xticks我得到以下圖:

#ax1.set_xticks(range(len(pop_plot.index))) 

Regular plot

我試過一對夫婦,我發現這裏的答案,但我並沒有多少成功。

在此先感謝。

+0

爲什麼你會想到'範圍(LEN())'會給值開始在1900? – roganjosh

+0

我不會。標籤由xticklabels = pop_plot.index提供。 – vgastaldi

+0

我不確定我能否理解這個問題。根據你的回答,我根本不明白'ax1.set_xticks(range(len(pop_plot.index))'的預期功能。另外,如果沒有看到數據,就不可能知道你爲什麼沒有得到 – roganjosh

回答

0

目前尚不清楚應使用什麼ax1.set_xticks(range(len(pop_plot.index)))。這將設置蜱的數字0,1,2,3等,而你的情節應爲1990年至2014年

相反,你要蜱設置爲您的數據的數量:

ax1.set_xticks(pop_plot.index) 

完全糾正例如:

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

index = np.arange(1990,2015,1) 
columns = ['Total Population','Urban Population'] 

pop_plot = pd.DataFrame(index=index, columns=columns) 

pop_plot['Total Population'] = np.arange(150,175,1) 
pop_plot['Urban Population'] = np.arange(50,125,3) 


fig = plt.figure(figsize=(10,5)) 
ax1 = fig.add_subplot(2,2,1) 

ax1.plot(pop_plot) 
legend = ax1.legend(pop_plot, bbox_to_anchor=(0.1, 1, 0.8, .45), loc=3, ncol=1, mode='expand') 
legend.get_frame().set_alpha(0) 

ax1.set_xticks(pop_plot.index) 
plt.show() 
+0

我不記得我是怎麼做到的,但使用你的答案,它完美的工作。 謝謝。 – vgastaldi