簡體   English   中英

Python pandas,繪制多行的選項

[英]Python pandas, Plotting options for multiple lines

我想從pandas數據框中繪制多條線,並為每條線設置不同的選項。 我想做點什么

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

這會引發一些錯誤消息:

  • linewidth不能用列表調用

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

還有一些東西對我來說似乎很奇怪

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

  • 如果我打電話給testdataframe[0].plot(style=['s-','o-','^-'],color=['b','r','y'])就可以了樣式列表,但沒有顏色列表

希望有人可以提供幫助,謝謝。

你真是太近了!

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

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)

在這種情況下並不實用,但這個概念可能會在以后派上用場。

考慮數據幀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]

我們可以在testdataframe上使用plot方法將列表styles傳遞給style參數。 請注意,我們也可以傳遞一個字典(也可能是其他東西)。

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

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

在此輸入圖像描述

所以我認為答案在於將顏色和樣式傳遞到同一個參數中。 以下示例適用於pandas 0.19.2:

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

不幸的是,似乎不能將多個線寬作為輸入傳遞給matplotlib。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM