2013-01-06 103 views
18

我想繪製熊貓數據框中的多行併爲每行設置不同的選項。我想這樣做Python熊貓,多行的繪圖選項

testdataframe=pd.DataFrame(np.arange(12).reshape(4,3)) 
testdataframe.plot(style=['s-','o-','^-'],color=['b','r','y'],linewidth=[2,1,1]) 

這將引發一些錯誤消息:

  • 線寬不調用一個列表

  • 在風格上,我不能使用的'和'o'或任何其他字母符號,當定義列表中的顏色時

此外,還有一些更多的東西,這似乎怪我

  • 當我添加另一個陰謀命令將上面的代碼testdataframe[0].plot()將繪製在同一張圖上這條線,如果我添加命令testdataframe[[0,1]].plot()它會創建一個新的情節

  • 如果我會打電話testdataframe[0].plot(style=['s-','o-','^-'],color=['b','r','y'])很精緻,在風格列表,但不與顏色列表

希望有人能幫助,謝謝。

回答

32

你太親近了!

您可以在樣式列表中指定的顏色:

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

testdataframe = pd.DataFrame(np.arange(12).reshape(4,3), columns=['A', 'B', 'C']) 
styles = ['bs-','ro-','y^-'] 
linewidths = [2, 1, 4] 
fig, ax = plt.subplots() 
for col, style, lw in zip(testdataframe.columns, styles, linewidths): 
    testdataframe[col].plot(style=style, lw=lw, ax=ax) 

還要注意的是plot方法可以採取matplotlib.axes對象,這樣你就可以多次調用像這樣(如果你想):

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

testdataframe1 = pd.DataFrame(np.arange(12).reshape(4,3), columns=['A', 'B', 'C']) 
testdataframe2 = pd.DataFrame(np.random.normal(size=(4,3)), columns=['D', 'E', 'F']) 
styles1 = ['bs-','ro-','y^-'] 
styles2 = ['rs-','go-','b^-'] 
fig, ax = plt.subplots() 
testdataframe1.plot(style=styles1, ax=ax) 
testdataframe2.plot(style=styles2, ax=ax) 

在這種情況下不太實際,但這個概念可能會在稍後派上用場。

+1

thx爲您提供幫助,但這對線寬無幫助?我也想使用一些自定義的顏色,比如own_color ='#FF0000',然後就不能這樣調用。 – Joerg

+0

然後我只能想到遍歷列。請參閱我對第一個示例的編輯。 –

+3

是的,這就是我現在使用的。但我只是想知道他們是否只是這種笨拙的方式來完成這樣一個簡單的任務。但非常感謝您的幫助! – Joerg

6

考慮到數據幀testdataframe

testdataframe = pd.DataFrame(np.arange(12).reshape(4,3)) 

print(testdataframe) 

    0 1 2 
0 0 1 2 
1 3 4 5 
2 6 7 8 
3 9 10 11 

您可以結合styles成字符串的一個列表,在styles定義如下。我也將在lws

styles=['bs-', 'ro-', 'y^-'] 
lws = [2, 1, 1] 

定義線寬我們可以用plot方法上testdataframe通過列表stylesstyle參數。請注意,我們也可以傳遞字典(也可能是其他的東西)。

但是,線寬不容易處理。我首先捕獲AxesSubplot對象並遍歷線屬性設置線寬。

ax = testdataframe.plot(style=styles) 
for i, l in enumerate(ax.lines): 
    plt.setp(l, linewidth=lws[i]) 

enter image description here

3

所以我認爲,答案就在於通過顏色和樣式相同的參數。以下示例適用於pandas 0.19。2:

testdataframe=pd.DataFrame(np.arange(12).reshape(4,3)) 
testdataframe.plot(style=['r*-','bo-','y^-'], linewidth=2.0) 

不幸的是,似乎將多行寬度作爲matplotlib的輸入傳遞是不可能的。