欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

一文教會你pandas?plot各種繪圖

 更新時間:2022年03月04日 11:23:03   作者:Buckletime  
這篇文章主要給大家介紹了關(guān)于pandas?plot各種繪圖的相關(guān)資料,文中通過圖文以及實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

一、介紹

使用pandas.DataFrame的plot方法繪制圖像會按照數(shù)據(jù)的每一列繪制一條曲線,默認按照列columns的名稱在適當?shù)奈恢谜故緢D例,比matplotlib繪制節(jié)省時間,且DataFrame格式的數(shù)據(jù)更規(guī)范,方便向量化及計算。

DataFrame.plot( )函數(shù)

DataFrame.plot(x=None, y=None, kind='line', ax=None, subplots=False, 
                sharex=None, sharey=False, layout=None, figsize=None, 
                use_index=True, title=None, grid=None, legend=True, 
                style=None, logx=False, logy=False, loglog=False, 
                xticks=None, yticks=None, xlim=None, ylim=None, rot=None, 
                fontsize=None, colormap=None, position=0.5, table=False, yerr=None, 
                xerr=None, stacked=True/False, sort_columns=False, 
                secondary_y=False, mark_right=True, **kwds)

1.1 參數(shù)介紹

  • x和y:表示標簽或者位置,用來指定顯示的索引,默認為None
  • kind:表示繪圖的類型,默認為line,折線圖
    • line:折線圖
    • bar/barh:柱狀圖(條形圖),縱向/橫向
    • pie:餅狀圖
    • hist:直方圖(數(shù)值頻率分布)
    • box:箱型圖
    • kde:密度圖,主要對柱狀圖添加Kernel 概率密度線
    • area:區(qū)域圖(面積圖)
    • scatter:散點圖
    • hexbin:蜂巢圖
  • ax:子圖,可以理解成第二坐標軸,默認None
  • subplots:是否對列分別作子圖,默認False
  • sharex:共享x軸刻度、標簽。如果ax為None,則默認為True,如果傳入ax,則默認為False
  • sharey:共享y軸刻度、標簽
  • layout:子圖的行列布局,(rows, columns)
  • figsize:圖形尺寸大小,(width, height)
  • use_index:用索引做x軸,默認True
  • title:圖形的標題
  • grid:圖形是否有網(wǎng)格,默認None
  • legend:子圖的圖例
  • style:對每列折線圖設(shè)置線的類型,list or dict
  • logx:設(shè)置x軸刻度是否取對數(shù),默認False
  • logy
  • loglog:同時設(shè)置x,y軸刻度是否取對數(shù),默認False
  • xticks:設(shè)置x軸刻度值,序列形式(比如列表)
  • yticks
  • xlim:設(shè)置坐標軸的范圍。數(shù)值,列表或元組(區(qū)間范圍)
  • ylim
  • rot:軸標簽(軸刻度)的顯示旋轉(zhuǎn)度數(shù),默認None
  • fontsize : int, default None#設(shè)置軸刻度的字體大小
  • colormap:設(shè)置圖的區(qū)域顏色
  • colorbar:柱子顏色
  • position:柱形圖的對齊方式,取值范圍[0,1],默認0.5(中間對齊)
  • table:圖下添加表,默認False。若為True,則使用DataFrame中的數(shù)據(jù)繪制表格
  • yerr:誤差線
  • xerr
  • stacked:是否堆積,在折線圖和柱狀圖中默認為False,在區(qū)域圖中默認為True
  • sort_columns:對列名稱進行排序,默認為False
  • secondary_y:設(shè)置第二個y軸(右輔助y軸),默認為False
  • mark_right : 當使用secondary_y軸時,在圖例中自動用“(right)”標記列標簽 ,默認True
  • x_compat:適配x軸刻度顯示,默認為False。設(shè)置True可優(yōu)化時間刻度的顯示

1.2 其他常用說明

  • color:顏色
  • s:散點圖大小,int類型
  • 設(shè)置x,y軸名稱
    • ax.set_ylabel(‘yyy’)
    • ax.set_xlabel(‘xxx’)

二、舉例說明

2.1 折線圖 line

1. 基本用法

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()
ts.plot();

2. 展示多列數(shù)據(jù)

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range("1/1/2000", periods=1000), columns=list("ABCD"))
df = df.cumsum()
df.plot()

3. 使用x和y參數(shù),繪制一列與另一列的對比

df3 = pd.DataFrame(np.random.randn(1000, 2), columns=["B", "C"]).cumsum()
df3["A"] = pd.Series(list(range(1000)))
df3.plot(x="A", y="B")

4. secondary_y參數(shù),設(shè)置第二Y軸及圖例位置

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
print(df)
# 圖1:其中A列用左Y軸標注,B列用右Y軸標注,二者共用一個X軸
df.A.plot()  # 對A列作圖,同理可對行做圖
df.B.plot(secondary_y=True)  # 設(shè)置第二個y軸(右y軸)
# 圖2
ax = df.plot(secondary_y=['A', 'B'])  # 定義column A B使用右Y軸。
# ax(axes)可以理解為子圖,也可以理解成對黑板進行切分,每一個板塊就是一個axes
ax.set_ylabel('CD scale')   # 主y軸標簽
ax.right_ax.set_ylabel('AB scale')  # 第二y軸標簽
ax.legend(loc='upper left')  # 設(shè)置圖例的位置
ax.right_ax.legend(loc='upper right')   # 設(shè)置第二圖例的位置

5. x_compat參數(shù),X軸為時間刻度的良好展示

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()
ts.plot(x_compat=True)

6. color參數(shù),設(shè)置多組圖形的顏色

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000),
                  columns=list('ABCD')).cumsum()
df.A.plot(color='red')
df.B.plot(color='blue')
df.C.plot(color='yellow')

2.2 條型圖 bar

DataFrame.plot.bar() 或者 DataFrame.plot(kind=‘bar’)

1. 基本用法

df2 = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
df2.plot.bar()

2. 參數(shù)stacked=True,生成堆積條形圖

df2.plot.bar(stacked=True)

3. 使用barh,生成水平條形圖

df2.plot.barh()

4. 使用rot參數(shù),設(shè)置軸刻度的顯示旋轉(zhuǎn)度數(shù)

df2.plot.bar(rot=0)	# 0表示水平顯示

2.3 直方圖 hist

1. 基本使用

df3 = pd.DataFrame(
    {
        "a": np.random.randn(1000) + 1,
        "b": np.random.randn(1000),
        "c": np.random.randn(1000) - 1,
    },
    columns=["a", "b", "c"],
)
# alpha設(shè)置透明度
df3.plot.hist(alpha=0.5)
# 設(shè)置坐標軸顯示負號
plt.rcParams['axes.unicode_minus']=False

2. 直方圖可以使用堆疊,stacked=True??梢允褂脜?shù) bins 更改素材箱大小

df3.plot.hist(alpha=0.5,stacked=True, bins=20)

3. 可以使用參數(shù) by 指定關(guān)鍵字來繪制分組直方圖

data = pd.Series(np.random.randn(1000))
data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4))

2.4 箱型圖 box

箱型圖,用來可視化每列中值的分布

.1. 基本使用

示例:這里有一個箱形圖,代表對[0,1]上的均勻隨機變量的10個觀察結(jié)果進行的五次試驗。

df = pd.DataFrame(np.random.rand(10, 5), columns=["A", "B", "C", "D", "E"])
df.plot.box();

2. 箱型圖可以通過參數(shù) color 進行著色

color是dict類型,包含的鍵分別是 boxes, whiskers, medians and caps

color = {
    "boxes": "DarkGreen",
    "whiskers": "DarkOrange",
    "medians": "DarkBlue",
    "caps": "Gray",
}
df.plot.box(color=color, sym="r+")

3. 可以使用參數(shù) vert=False,指定水平方向顯示,默認為True表示垂直顯示

df.plot.box(vert=False)

4. 可以使用boxplot()方法,繪制帶有網(wǎng)格的箱型圖

df = pd.DataFrame(np.random.rand(10, 5))
bp = df.boxplot()

5. 可以使用參數(shù) by 指定關(guān)鍵字來繪制分組箱型圖

df = pd.DataFrame(np.random.rand(10, 2), columns=["Col1", "Col2"])
df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
bp = df.boxplot(by="X")

6. 可以使用多個列進行分組

df = pd.DataFrame(np.random.rand(10, 3), columns=["Col1", "Col2", "Col3"])
df["X"] = pd.Series(["A", "A", "A", "A", "A", "B", "B", "B", "B", "B"])
df["Y"] = pd.Series(["A", "B", "A", "B", "A", "B", "A", "B", "A", "B"])
bp = df.boxplot(column=["Col1", "Col2"], by=["X", "Y"])

2.5 區(qū)域圖 area

默認情況下,區(qū)域圖為堆疊。要生成區(qū)域圖,每列必須全部為正值或全部為負值。

1. 基本使用

df = pd.DataFrame(np.random.rand(10, 4), columns=["a", "b", "c", "d"])
df.plot.area()

2.6 散點圖 scatter

散點圖需要x和y軸的數(shù)字列。 這些可以由x和y關(guān)鍵字指定。

1. 基本使用

df = pd.DataFrame(np.random.rand(50, 4), columns=["a", "b", "c", "d"])
df["species"] = pd.Categorical(
    ["setosa"] * 20 + ["versicolor"] * 20 + ["virginica"] * 10
)
df.plot.scatter(x="a", y="b")

2. 可以使用 參數(shù) ax 和 label 設(shè)置多組數(shù)據(jù)

ax = df.plot.scatter(x="a", y="b", color="DarkBlue", label="Group 1")
df.plot.scatter(x="c", y="d", color="DarkGreen", label="Group 2", ax=ax)

3. 使用參數(shù) c 可以作為列的名稱來為每個點提供顏色,參數(shù)s可以指定散點大小

df.plot.scatter(x="a", y="b", c="c", s=50)

4. 如果將一個分類列傳遞給c,那么將產(chǎn)生一個離散的顏色條

df.plot.scatter(x="a", y="b", c="species", cmap="viridis", s=50)

5. 可以使用DataFrame的一列值作為散點的大小

df.plot.scatter(x="a", y="b", s=df["c"] * 200)

2.7 蜂巢圖 hexbin

如果數(shù)據(jù)過于密集而無法單獨繪制每個點,則 蜂巢圖可能是散點圖的有用替代方法。

df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
df["b"] = df["b"] + np.arange(1000)
df.plot.hexbin(x="a", y="b", gridsize=25)

2.8 餅型圖 pie

如果您的數(shù)據(jù)包含任何NaN,則它們將自動填充為0。 如果數(shù)據(jù)中有任何負數(shù),則會引發(fā)ValueError

1. 基本使用

series = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"], name="series")
series.plot.pie(figsize=(6, 6))

2. 如果指定subplot =True,則將每個列的餅圖繪制為子圖。 默認情況下,每個餅圖中都會繪制一個圖例; 指定legend=False隱藏它。

df = pd.DataFrame(
    3 * np.random.rand(4, 2), index=["a", "b", "c", "d"], columns=["x", "y"]
)
df.plot.pie(subplots=True, figsize=(8, 4))

3. autopct 顯示所占總數(shù)的百分比

series.plot.pie(
    labels=["AA", "BB", "CC", "DD"],
    colors=["r", "g", "b", "c"],
    autopct="%.2f",	
    fontsize=20,
    figsize=(6, 6),
)

三、其他格式

3.1 設(shè)置顯示中文標題

df = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
df.plot.bar(title='中文標題測試',rot=0)
# 默認不支持中文 ---修改RC參數(shù),指定字體
plt.rcParams['font.sans-serif'] = 'SimHei'

3.2 設(shè)置坐標軸顯示負號

df3 = pd.DataFrame(
    {
        "a": np.random.randn(1000) + 1,
        "b": np.random.randn(1000),
        "c": np.random.randn(1000) - 1,
    },
    columns=["a", "b", "c"],
)
df3.plot.hist(alpha=0.5)
# 設(shè)置坐標軸顯示負號
plt.rcParams['axes.unicode_minus']=False

3.3 使用誤差線 yerr 進行繪圖

示例1:使用與原始數(shù)據(jù)的標準偏繪制組均值

ix3 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['foo', 'foo', 'bar', 'bar', 'foo', 'foo', 'bar', 'bar']], names=['letter', 'word'])
df3 = pd.DataFrame({'data1': [3, 2, 4, 3, 2, 4, 3, 2], 'data2': [6, 5, 7, 5, 4, 5, 6, 5]}, index=ix3) 
# 分組
gp3 = df3.groupby(level=('letter', 'word'))
means = gp3.mean() 
errors = gp3.std() 
means.plot.bar(yerr=errors,rot=0)

示例2:使用非對稱誤差線繪制最小/最大范圍

mins = gp3.min()
maxs = gp3.max()
errors = [[means[c] - mins[c], maxs[c] - means[c]] for c in df3.columns]
means.plot.bar(yerr=errors,capsize=4, rot=0)

3.4 使用 layout 將目標分成多個子圖

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range("1/1/2000", periods=1000), columns=list("ABCD"))
df = df.cumsum()
df.plot(subplots=True, layout=(2, 3), figsize=(6, 6), sharex=False)

3.5 使用 table 繪制表,上圖下表

使用 table=True,繪制表格。圖下添加表

fig, ax = plt.subplots(1, 1, figsize=(7, 6.5))
df = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])
ax.xaxis.tick_top()  # 在上方展示x軸
df.plot(table=True, ax=ax)

3.6 使用 colormap 設(shè)置圖的區(qū)域顏色

在繪制大量列時,一個潛在的問題是,由于默認顏色的重復,很難區(qū)分某些序列。 為了解決這個問題,DataFrame繪圖支持使用colormap參數(shù),該參數(shù)接受Matplotlib的colormap或一個字符串,該字符串是在Matplotlib中注冊的一個colormap的名稱。 在這里可以看到默認matplotlib顏色映射的可視化。

df = pd.DataFrame(np.random.randn(1000, 10), index=pd.date_range("1/1/2000", periods=1000))
df = df.cumsum()
df.plot(colormap="cubehelix")

參考文章:http://www.dbjr.com.cn/article/188648.htm

總結(jié)

到此這篇關(guān)于pandas plot各種繪圖的文章就介紹到這了,更多相關(guān)pandas plot各種繪圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python內(nèi)置模塊Collections的使用教程詳解

    Python內(nèi)置模塊Collections的使用教程詳解

    collections 是 Python 的一個內(nèi)置模塊,所謂內(nèi)置模塊的意思是指 Python 內(nèi)部封裝好的模塊,無需安裝即可直接使用。本文將詳解介紹Collections的使用方式,需要的可以參考一下
    2022-03-03
  • matplotlib之Font family [‘sans-serif‘] not found的問題解決

    matplotlib之Font family [‘sans-serif‘] not&nbs

    本文主要介紹了matplotlib之Font family [‘sans-serif‘] not found的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-03-03
  • python如何獲取服務(wù)器硬件信息

    python如何獲取服務(wù)器硬件信息

    這篇文章主要為大家詳細介紹了python獲取服務(wù)器硬件信息的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • python編程羊車門問題代碼示例

    python編程羊車門問題代碼示例

    這篇文章主要介紹了python編程“羊車門”問題代碼示例,初步接觸,僅供參考。不足之處,歡迎指出。
    2017-10-10
  • python numpy實現(xiàn)文件存取的示例代碼

    python numpy實現(xiàn)文件存取的示例代碼

    這篇文章主要介紹了python numpy實現(xiàn)文件存取的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-05-05
  • 2023巨詳細的Python安裝庫教程(以pycharm和Anaconda安裝pygame為例)

    2023巨詳細的Python安裝庫教程(以pycharm和Anaconda安裝pygame為例)

    這篇文章主要給大家介紹了巨詳細的Python安裝庫教程,文中以pycharm和Anaconda安裝pygame為例,通過圖文介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • Python使用PyMongo4.x操作MongoDB的教程分享

    Python使用PyMongo4.x操作MongoDB的教程分享

    PyMongo是一個Python編程語言中用于連接和操作MongoDB數(shù)據(jù)庫的庫,它提供了豐富的功能和API,使開發(fā)者能夠在Python中輕松地進行MongoDB的數(shù)據(jù)交互和管理,本文給大家總結(jié)了Python如何使用PyMongo4.x操作MongoDB,需要的朋友可以參考下
    2023-09-09
  • python多進程實現(xiàn)文件下載傳輸功能

    python多進程實現(xiàn)文件下載傳輸功能

    這篇文章主要為大家詳細介紹了python多進程實現(xiàn)文件下載傳輸功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • python實現(xiàn)點對點聊天程序

    python實現(xiàn)點對點聊天程序

    這篇文章主要為大家詳細介紹了python實現(xiàn)點對點聊天程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python?selenium把歌詞評論做成詞云圖

    Python?selenium把歌詞評論做成詞云圖

    大家好,本篇文章主要講的是Python?selenium把歌詞評論做成詞云圖,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-01-01

最新評論