2016-12-20 54 views
0

我已經繪製兩個y軸的圖表,現在想加兩個獨立的趨勢線每個在y地塊。如何添加多個趨勢線大熊貓

這是我的代碼:

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

amp_costs=pd.read_csv('/Users/Ampicillin_Costs.csv', index_col=None, usecols=[0,1,2]) 
amp_costs.columns=['PERIOD', 'ITEMS', 'COST PER ITEM'] 

ax=amp_costs.plot(x='PERIOD', y='COST PER ITEM', color='Blue', style='.', markersize=10) 
amp_costs.plot(x='PERIOD', y='ITEMS', secondary_y=True, 
color='Red', style='.', markersize=10, ax=ax) 

至於如何繪製這兩個趨勢線該圖形的任何指導,將不勝感激!

+0

看起來你在你的代碼就是這樣做的。問題是什麼?你得到了什麼樣的輸出?請爲我們製作一個最小可重複的示例。這使得以這種方式回答問題變得更加容易。 http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples –

+0

什麼樣的趨勢線的?線性?滾動平均?什麼不在你的代碼中工作?你有什麼嘗試? –

+0

@DemetriP線性...這個代碼工作正常但是我不能確定在哪裏,以增加2條趨勢線開始 - 1每組數據繪製的。 –

回答

1

下面是如何使用sklearn.linear_model.LinearRegression,使趨勢線一個簡單的例子。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
from sklearn.linear_model import LinearRegression 
plt.style.use('ggplot') 
%matplotlib inline 

period = np.arange(10) 
items = -2*period +1 + np.random.randint(-2,2,len(period)) 
cost = 35000*period +15000 + np.random.randint(-25000,25000,len(period)) 
data = np.vstack((period,items,cost)).T 
df = pd.DataFrame(data, columns=\['P','ITEMS', 'COST'\]).set_index('P') 


lmcost = LinearRegression().fit(period.reshape(-1,1), cost.reshape(-1,1)) 
lmitems = LinearRegression().fit(period.reshape(-1,1), items.reshape(-1,1)) 

df['ITEMS_LM'] = lmitems.predict(period.reshape(-1,1)) 
df['COST_LM'] = lmcost.predict(period.reshape(-1,1)) 

fig,ax = plt.subplots() 


df.ITEMS.plot(ax = ax, color = 'b') 
df.ITEMS_LM.plot(ax = ax,color= 'b', linestyle= 'dashed') 
df.COST.plot(ax = ax, secondary_y=True, color ='g') 
df.COST_LM.plot(ax = ax, secondary_y=True, color = 'g', linestyle='dashed') 

enter image description here

+0

'amp_costs = pd.read_csv('/ Users/Ampicillin_Costs.csv',index_col = None,usecols = [1,2]) amp_costs.columns = ['ITEMS','每項成本'] z = np。 polyfit(X = amp_costs.loc [:, amp_costs [ '每項價格']],Y = amp_costs.loc [:, amp_costs [ 'ITEMS']],DEG = 1) p = np.poly1d(Z) amp_costs [ '趨勢線'] = p(amp_costs.loc [:, amp_costs [ '每項價格']]) X = amp_costs [ '每項價格'] Y = amp_costs [ 'ITEMS'] AX = amp_costs .plot.scatter(X,Y) amp_costs.set_index(X,就地=真) amp_costs.trendline.sort_index(升序=假).plot(AX = AX) plt.gca()。invert_xaxis() PLT 。顯示()' –