2016-02-05 104 views
0

我想將x軸更改爲幾年。這些年是可變年份的節省。X標籤matplotlib

我想讓我的數據的情節,看起來像這樣: It should look like this image

但是,我不能用年創建X軸。我的情節看起來像下面的圖片: This is an example of produced image by my code

我的代碼如下:

import pandas as pd 
import matplotlib.pyplot as plt 

data = pd.read_csv("data1.csv") 
demand = data["demand"] 
years = data["year"] 
plt.plot(demand, color='black') 
plt.xlabel("Year") 
plt.ylabel("Demand (GW)") 
plt.show() 

我很感謝任何意見。

+0

'plt.plot(年需求量,顏色= '黑')'假設年是2002年,2003等 –

+0

你好@JensMunk。感謝您的建議,但它不起作用。它產生如下結果:http://i.stack.imgur.com/Q2Wfk.png – user3304071

+0

嗯。你顯示的情節似乎只包含較少的點數。 –

回答

1

您示例中的plot方法不知道數據的縮放比例。因此,爲了簡單起見,它將demand的值視爲彼此相距一個單位。如果您希望x軸代表多年,則必須告知matplotlibdemand應將其視爲「一年」。如果您的數據是按月需求,那麼顯然每年有12個值。在這裏,我們去:

# setup a figure 
fig, (ax1, ax2) = plt.subplots(2) 

# generate some random data 
data = np.random.rand(100) 

# plot undesired way 
ax1.plot(data) 

# change the tick positions and labels ... 
ax2.plot(data) 

# ... to one label every 12th value 
xticks = np.arange(0,100,12) 

# ... start counting in the year 2000 
xlabels = range(2000, 2000+len(xticks)) 

ax2.set_xticks(xticks) 
ax2.set_xticklabels(xlabels) 

plt.show() 
+0

非常感謝。它運作良好。 – user3304071