Pandas數(shù)據(jù)可視化原來也這么厲害

一、可視化概述
在Python中,常見的數(shù)據(jù)可視化庫有3個:
matplotlib:最常用的庫,可以算作可視化的必備技能庫,比較底層,api多,學(xué)起來不太容易。
seaborn:是建構(gòu)于matplotlib基礎(chǔ)上,能滿足絕大多數(shù)可視化需求,更特殊的需求還是需要學(xué)習(xí)matplotlib。
pyecharts:上面的兩個庫都是靜態(tài)的可視化庫,而pyecharts有很好的web兼容性,可以做到可視化的動態(tài)效果。并且種類也比較豐富。比如這個圖,就非常厲害:畫圖神器pyecharts-旭日圖
Pandas:而今天要講的是Pandas的可視化,Pandas主要作為數(shù)據(jù)分析的庫,雖然沒有上述三個庫那個強大,但是勝在方便,在數(shù)據(jù)分析的過程中,只要一行代碼就能實現(xiàn)。并且圖形也非常漂亮。
二、直接看案例
Pandas 中,有11個比較常見的圖形可視化,還有幾個比較進階的,我們一個一個看看怎么畫的
import pandas as pdimport numpy as npdf= pd.DataFrame(np.random.rand(10, 4), columns=['A','B','C','D'])
01、柱狀圖-縱向
df.plot.bar()
? ? ? ?
? ? ?
stacked=True,畫堆疊柱狀圖
df.plot.bar(stacked=True)
? ? ? ?
? ? ?
?
02、柱狀圖-橫向
df.plot.barh()
? ? ? ?
? ? ?
同樣,stacked=True,畫堆疊柱狀圖
df.plot.barh(stacked=True)
? ? ? ?
? ? ?
?
03、面積圖
df.plot.area(alpha = 0.9)
? ? ? ?
? ? ?
df.plot.area(stacked=True,alpha = 0.9)
? ? ? ?
? ? ?
04、密度圖-kde
df.plot.kde()
? ? ? ?
? ? ?
05、密度圖-density
df.plot.density()
? ? ? ?
? ? ?
?
06、直方圖
換個數(shù)據(jù)集
df = pd.DataFrame({'A': np.random.randn(1000) + 1,'B': np.random.randn(1000),'C': np.random.randn(1000) - 1},columns=['A', 'B', 'C'])df.plot.hist(bins=200)
? ? ? ?
? ? ?
df.plot.hist(stacked=True, bins=20)
? ? ? ?
? ? ?
?
df= pd.DataFrame(np.random.rand(1000, 4), columns=['A','B','C','D'])df.diff().hist(color='k', alpha=0.7, bins=50)
? ? ? ?
? ? ?
?
07、箱盒圖
df= pd.DataFrame(np.random.rand(100, 4), columns=['A','B','C','D'])df.plot.box()
? ? ? ?
? ? ?
vert=False也可以換成橫向
df.plot.box(vert=False)
? ? ? ?
? ? ?
?
08、散點圖
df.plot.scatter(x='A',y='B')
? ? ? ?
? ? ?
?
09、蜂巢圖
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)
?
? ? ? ?
? ? ?
07、餅圖
series = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')series.plot.pie(figsize=(6, 6))
? ? ? ?
? ? ?
series.plot.pie(labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'],autopct='%.2f', fontsize=20, figsize=(6, 6))
? ? ? ?
? ? ?
?
08、矩陣散點圖
from pandas.plotting import scatter_matrixdf = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
? ? ? ?
? ? ?
?
09、安德魯斯曲線
加載自己的數(shù)據(jù),關(guān)注公眾號【AI入門學(xué)習(xí)】回復(fù)?iris 獲取數(shù)據(jù)集
data = pd.read_csv('C:/Users/wuzhengxiang/Desktop/iris.csv')pd.plotting.andrews_curves(data , 'Name')
? ? ? ?
? ? ?
andrews_curves(data, 'Name', colormap='winter')
? ? ? ?
? ? ?
?
10、平行坐標(biāo)圖
該圖也是使用自己加載的iris數(shù)據(jù)集
from pandas.plotting import parallel_coordinatesparallel_coordinates(data, 'Name', colormap='gist_rainbow')
? ? ? ?
? ? ?
?
11、Lag Plot
from pandas.plotting import lag_plotdf= pd.Series(0.1 * np.random.rand(1000) +0.9 * np.sin(np.linspace(-99 * np.pi, 99 * np.pi, num=1000)))lag_plot(df)
? ? ? ?
? ? ?
?
12、默認函數(shù)plot
直接畫圖,默認為折線圖
df= pd.DataFrame(np.random.rand(12, 4), columns=['A','B','C','D'])df.plot()
? ? ? ?
? ? ?
df.plot(subplots=True,layout=(2, 2), figsize=(15, 8))
? ? ? ?
df= pd.DataFrame(np.random.rand(1000, 4), columns=['A','B','C','D'])df.plot()
? ? ? ?
? ? ?
df.plot(subplots=True,layout=(2,?2),?figsize=(15,?8))
? ? ? ?
? ? ?
?
13、bootstrap_plot
s = pd.Series(np.random.uniform(size=100))pd.plotting.bootstrap_plot(s)
? ? ? ?
? ? ?
?
?
三、參數(shù)詳解
1、官方文檔
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html
https://pandas.pydata.org/pandas-docs/version/0.18.1/visualization.html
2、參數(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)
e, 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)
注意:每種繪圖類型都有相對應(yīng)的方法: df.plot(kind='line')與df.plot.line()等價
x : label or position, default None#指數(shù)據(jù)列的標(biāo)簽或位置參數(shù)
y : label, position or list of label, positions, default None
kind : str#繪圖類型
‘line’ : line plot (default)#折線圖
‘bar’ : vertical bar plot#條形圖。stacked為True時為堆疊的柱狀圖
‘barh’ : horizontal bar plot#橫向條形圖
‘hist’ : histogram#直方圖(數(shù)值頻率分布)
‘box’ : boxplot#箱型圖
‘kde’ : Kernel Density Estimation plot#密度圖,主要對柱狀圖添加Kernel 概率密度線
‘density’ : same as ‘kde’
‘a(chǎn)rea’ : area plot#與x軸所圍區(qū)域圖(面積圖)。Stacked=True時,每列必須全部為正或負值,stacked=False時,對數(shù)據(jù)沒有要求
‘pie’ : pie plot#餅圖。數(shù)值必須為正值,需指定Y軸或者subplots=True
‘scatter’ : scatter plot#散點圖。需指定X軸Y軸
‘hexbin’ : hexbin plot#蜂巢圖。需指定X軸Y軸
‘hexbin’ : hexbin plot#蜂巢圖。需指定X軸Y軸
ax : matplotlib axes object, default None#**子圖(axes, 也可以理解成坐標(biāo)軸) 要在其上進行繪制的matplotlib subplot對象。如果沒有設(shè)置,則使用當(dāng)前matplotlib subplot**其中,變量和函數(shù)通過改變figure和axes中的元素(例如:title,label,點和線等等)一起描述figure和axes,也就是在畫布上繪圖。
subplots : boolean, default False#是否對列分別作子圖
sharex : boolean, default True if ax is None else False#如果ax為None,則默認為True,否則為False
In case subplots=True, share x axis and set some x axis labels to invisible; defaults to True if ax is None otherwise False if an ax is passed in; Be aware, that passing in both an ax and sharex=True will alter all x axis labels for all axis in a figure!
sharey : boolean, default False#如果有子圖,子圖共y軸刻度,標(biāo)簽
In case subplots=True, share y axis and set some y axis labels to invisible
layout : tuple (rows, columns) for the layout of subplots#子圖的行列布局
figsize : a tuple (width, height) in inches#圖片尺寸大小
use_index : boolean, default True#默認用索引做x軸
title : string#圖片的標(biāo)題用字符串
Title to use for the plot
grid : boolean, default None#圖片是否有網(wǎng)格
legend : False/True/’reverse’#子圖的圖例 (默認為True)
style : list or dict#對每列折線圖設(shè)置線的類型
logx : boolean, default False#設(shè)置x軸刻度是否取對數(shù)
logy : boolean, default False
loglog : boolean, default False#同時設(shè)置x,y軸刻度是否取對數(shù)
xticks : sequence#設(shè)置x軸刻度值,序列形式(比如列表)
yticks : sequence#設(shè)置y軸刻度,序列形式(比如列表)
xlim : float/2-tuple/list#設(shè)置坐標(biāo)軸的范圍。數(shù)值(最小值),列表或元組(區(qū)間范圍)
ylim : float/2-tuple/list
rot : int, default None#設(shè)置軸標(biāo)簽(軸刻度)的顯示旋轉(zhuǎn)度數(shù) ?
fontsize : int, default None#設(shè)置軸刻度的字體大小
colormap : str or matplotlib colormap object, default None#設(shè)置圖的區(qū)域顏色
colorbar : boolean, optional? #柱子顏色
If True, plot colorbar (only relevant for ‘scatter’ and ‘hexbin’ plots)
position : float? #條形圖的對齊方式,取值范圍[0,1],即左下端到右上端默認0.5(中間對齊)?
layout : tuple (optional)? #布局。layout=(2, 3)兩行三列,layout=(2, -1)兩行自適應(yīng)列數(shù)
Eg. df.plot(subplots=True, layout=(2, -1), sharex=False)
table : boolean, Series or DataFrame, default False ?#圖下添加表。如果為True,則使用DataFrame中的數(shù)據(jù)繪制表格,并且數(shù)據(jù)將被轉(zhuǎn)置以滿足matplotlib的默認布局。。
yerr : DataFrame, Series, array-like, dict and str
See Plotting with Error Bars for detail.
xerr : same types as yerr.
stacked : boolean, default False in line and bar plots, and True in area plot. If True, create stacked plot. #前面有介紹
sort_columns : boolean, default False? #對列名稱進行排序以確定繪圖順序
secondary_y : boolean or sequence, default False? #設(shè)置第二個y軸(右輔助y軸)
Whether to plot on the secondary y-axis If a?list/tuple, which columns to plot on secondary y-axis
mark_right : boolean, default True
↓掃描二維碼關(guān)注本號↓
