# 設(shè)置cell多行輸出
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all' #默認(rèn)為'last'
# 導(dǎo)入相關(guān)庫(kù)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
import os
warnings.filterwarnings('ignore')
os.chdir(r'E:\python_learn\data\data_for_kaggle')
file_name = 'kaggle_bike_train.csv'
data = pd.read_csv(file_name)
data.head()

data.isna().sum().sum() # 無(wú)缺失
data.info()
0
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10886 entries, 0 to 10885
Data columns (total 12 columns):
datetime 10886 non-null object
season 10886 non-null int64
holiday 10886 non-null int64
workingday 10886 non-null int64
weather 10886 non-null int64
temp 10886 non-null float64
atemp 10886 non-null float64
humidity 10886 non-null int64
windspeed 10886 non-null float64
casual 10886 non-null int64
registered 10886 non-null int64
count 10886 non-null int64
dtypes: float64(3), int64(8), object(1)
memory usage: 1020.6+ KB
data['datetime']=pd.to_datetime(data['datetime'])
data['month'] = data['datetime'].dt.month
data['weekday'] = data['datetime'].dt.weekday_name.str[:4]
data.head()
data.info()

柱狀圖 → plt.plot(kind='bar')/plt.bar()
柱狀圖:是一種以長(zhǎng)方形的長(zhǎng)度為變量的統(tǒng)計(jì)圖表。長(zhǎng)條圖用來(lái)比較兩個(gè)或以上的價(jià)值(不同時(shí)間或者不同條件),只有一個(gè)變量,通常利用于較小的數(shù)據(jù)集分析。
適用場(chǎng)景:適用場(chǎng)合是二維數(shù)據(jù)集(每個(gè)數(shù)據(jù)點(diǎn)包括兩個(gè)值x和y),但只有一個(gè)維度需要比較,用于顯示一段時(shí)間內(nèi)的數(shù)據(jù)變化或顯示各項(xiàng)之間的比較情況。
優(yōu)勢(shì):柱狀圖利用柱子的高度,反映數(shù)據(jù)的差異,肉眼對(duì)高度差異很敏感。
劣勢(shì):柱狀圖的局限在于只適用中小規(guī)模的數(shù)據(jù)集。
data_m = data.groupby('month').mean()['count'] # 按月統(tǒng)計(jì)租車量
# 柱狀圖繪制按月統(tǒng)計(jì)租車量count
# 單系列柱狀圖
data_m.plot(kind='bar',color='r',alpha=0.5,width=0.8,figsize=(12,8),rot=45) # data_m 為series,series.plot()
plt.title('單系列柱狀圖',fontsize=18,pad=12) # 設(shè)置標(biāo)題
plt.ylabel('y軸標(biāo)簽設(shè)置') # 設(shè)置y軸標(biāo)簽,x軸標(biāo)簽→plt.xlabel()
plt.grid(True,ls='--',lw=0.8,alpha=0.5,color='gray',axis='y') # 設(shè)置網(wǎng)格,axis='y',只顯示y軸網(wǎng)格,默認(rèn)xy都顯示
plt.ylim([0,300]) # 設(shè)置y軸標(biāo)尺的范圍
for x,y in zip(range(len(data_m)),data_m):
plt.text(x,y,'%.f'%y,ha='center',va='bottom',fontsize=12) # 給柱狀圖添加文字注釋

# 多系列柱狀圖
data_m_2 = data.groupby('month',as_index=False).mean()[['casual','registered']]
data_m_2.plot(kind='bar',figsize=(12,8),width=0.8)
for i,j in zip(range(len(data_m_2)),data_m_2['casual']):
plt.text(i-0.2,j+3,'%.f'%j,color='black',ha='center',va='center_baseline',fontsize=12)
for i,j in zip(range(len(data_m_2)),data_m_2['registered']):
plt.text(i+0.2,j+2,'%.f'%j,color='black',ha='center',va='center_baseline',fontsize=12)
plt.legend(loc=0) # 設(shè)置圖例,loc=0自定適配位置
plt.title('多系列柱狀圖',fontsize=18,pad=12)

柱狀圖延申圖表
條形圖 → plt.plot(kind='barh')
條形圖:是用寬度相同的條形的高度或長(zhǎng)短來(lái)表示數(shù)據(jù)多少的圖形,與柱狀圖類似,條形圖縱置就是柱狀圖
適用場(chǎng)景:顯示各個(gè)項(xiàng)目之間的比較情況,和柱狀圖類似的作用
優(yōu)勢(shì):每個(gè)條都清晰表示數(shù)據(jù),直觀;易于比較數(shù)據(jù)之間的差別
# 條形圖繪制按月統(tǒng)計(jì)租車量count
data_m.plot(kind='barh',figsize=(12,8),alpha=0.5,width=0.8,color='b')
plt.xlabel('count')
plt.title('柱狀圖延申圖-條形圖',fontsize=18,pad=12)
# 給條形圖標(biāo)注文字注釋略有不同
for x,y in zip(data_m,range(len(data_m))):
plt.text(x,y,'%.f'%x,ha='left',va='center',fontsize=12,color='r') # 給柱狀圖添加文字注釋

堆疊圖 → plt.plot(kind='bar/barh',stacked=True)
堆疊圖:顯示單個(gè)項(xiàng)目與整體之間的關(guān)系。
優(yōu)勢(shì):堆疊圖能夠使人們一眼看出各個(gè)數(shù)據(jù)的大小,易于比較數(shù)據(jù)之間的差別。利用條狀的長(zhǎng)度,反映數(shù)據(jù)的差異,肉眼對(duì)長(zhǎng)短差異很敏感,可以使得數(shù)據(jù)更加直觀,且堆疊圖不僅僅可以直觀的看出每個(gè)系列的值,還能夠反映出系列的總和,尤其是當(dāng)需要看某一單位的綜合以及各系列值的比重時(shí),最適合使用堆疊圖。
# 垂直堆疊
data_m_2.plot(kind='bar',stacked=True,figsize=(12,8),alpha=0.7)
plt.xlabel('month')
plt.ylabel('count')
plt.title('柱狀圖延伸圖-堆疊圖',fontsize=18,pad=12)
for i,j in zip(range(len(data_m_2)),data_m_2['casual']):
plt.text(i,j,'%.f'%j,color='black',ha='center',va='top',fontsize=12)
for i,j in zip(range(len(data_m_2)),data_m_2['registered']):
plt.text(i,j,'%.f'%j,color='black',ha='center',va='center_baseline',fontsize=12)

# 水平堆疊
data_m_2.plot(kind='barh',stacked=True,figsize=(12,8),alpha=0.7,width=0.7)
plt.xlabel('month')
plt.ylabel('count')
plt.title('柱狀圖延伸圖-堆疊圖',fontsize=18,pad=12)
for i,j in zip(data_m_2['casual'],range(len(data_m_2))):
plt.text(i,j,'%.f'%i,color='black',ha='right',va='center',fontsize=12)
for i,j in zip(data_m_2['registered'],range(len(data_m_2))):
plt.text(i,j,'%.f'%i,color='black',ha='left',va='center',fontsize=12)
u = data_m.mean()
plt.axvline(u,ls='--',c='b',lw=1,alpha=0.8,) # 添加垂直輔助線
plt.text(u,0,'%.2f'%u,color='blue',fontsize=14,bbox=dict(facecolor='yellow', alpha=0.5))

折線圖 → plt.plot(kind='line')
折線圖:折線圖可以顯示隨時(shí)間而變化的連續(xù)數(shù)據(jù),因此非常適用于顯示在相等時(shí)間間隔下數(shù)據(jù)的趨勢(shì)。
適用場(chǎng)景: 折線圖適合二維的大數(shù)據(jù)集,還適合多個(gè)二維數(shù)據(jù)集的比較。
優(yōu)勢(shì):容易反應(yīng)出數(shù)據(jù)變化的趨勢(shì)。
# 折線圖繪制按月統(tǒng)計(jì)租車量count
data_m.plot(figsize=(8,6),style='bo--') # 設(shè)置style可同時(shí)設(shè)置線段顏色,標(biāo)記,和線段樣式,但必須把顏色寫在最前面
u = data_m.mean()
plt.xlim([1,12])
plt.axhline(u,ls='--',c='r',lw=0.8,alpha=0.5,) # 添加水平輔助線
plt.text(data_m.index[-1]+0.2,u,'%.2f'%u,color='r',fontsize=14) # 標(biāo)注
plt.title('折線圖',fontsize=18,pad=12)

data_m_2.plot(figsize=(8,6),style='x--')
plt.legend(loc=0)
ma = data_m_2['registered'].max()
plt.grid(True,linestyle='--',linewidth=0.5,color='gray',axis='y',alpha=0.5)
plt.text(data_m_2.index[5],ma,'%.2f'%ma,fontsize=12,bbox=dict(facecolor='red', alpha=0.5)) # 標(biāo)注某個(gè)點(diǎn)
plt.title('折線圖',fontsize=18,pad=12)

直方圖 → plt.hist()
直方圖:又稱質(zhì)量分布圖,是一種統(tǒng)計(jì)報(bào)告圖,一般用橫軸表示數(shù)據(jù)類型,縱軸表示分布情況。
適用場(chǎng)景:觀察數(shù)據(jù)集的分布情況
優(yōu)勢(shì):直觀觀察數(shù)據(jù)形狀,突出顯示數(shù)據(jù)的中心趨勢(shì),確定數(shù)據(jù)樣本的分布是對(duì)稱還是偏斜
# 直方圖繪制temp
data['temp'].hist(bins=30,figsize=(8,6),edgecolor='black')
# bins,設(shè)置箱子數(shù)量
# edgecolor,設(shè)置邊框顏色
plt.title('直方圖',fontsize=18,pad=12)

data['temp'].hist(bins=30,figsize=(8,6),density=True)
# 參數(shù)density是關(guān)鍵,y軸會(huì)按百分比表示
# density=False,表示決定將y軸的取值范圍落在某個(gè)箱子中的元素的個(gè)數(shù),即系y軸表示頻率次數(shù)
# density=True,表示決定將y軸的取值范圍落在某個(gè)箱子中的元素的個(gè)數(shù)占總體的百分比,即系y軸表示百分比
plt.grid(False)
plt.title('直方圖',fontsize=18,pad=12)
data['temp'].plot(kind='kde',color='r') # 密度圖在直方圖參數(shù)density=True時(shí),和直方圖一起使用

餅圖 → plt.pie()
適用場(chǎng)景:顯示各項(xiàng)的大小與各項(xiàng)總和的比例。適用簡(jiǎn)單的占比比例圖,在不要求數(shù)據(jù)精細(xì)的情況適用。
優(yōu)勢(shì):明確顯示數(shù)據(jù)的比例情況,尤其合適渠道來(lái)源分析等場(chǎng)景。
劣勢(shì):數(shù)據(jù)類別較多時(shí)不適用
參數(shù):
x :(每一塊)的比例,如果sum(x) > 1會(huì)使用sum(x)歸一化;
labels :(每一塊)餅圖外側(cè)顯示的說(shuō)明文字;
explode :(每一塊)離開(kāi)中心距離;
startangle :起始繪制角度,默認(rèn)圖是從x軸正方向逆時(shí)針畫起,如設(shè)定=90則從y軸正方向畫起;
shadow :在餅圖下面畫一個(gè)陰影。默認(rèn)值:False,即不畫陰影;
labeldistance :label標(biāo)記的繪制位置,相對(duì)于半徑的比例,默認(rèn)值為1.1, 如<1則繪制在餅圖內(nèi)側(cè);
autopct :控制餅圖內(nèi)百分比設(shè)置,可以使用format字符串或者format function
'%1.1f'指小數(shù)點(diǎn)前后位數(shù)(沒(méi)有用空格補(bǔ)齊);
pctdistance :類似于labeldistance,指定autopct的位置刻度,默認(rèn)值為0.6;
radius :控制餅圖半徑,默認(rèn)值為1;
counterclock :指定指針?lè)较?;布爾值,可選參數(shù),默認(rèn)為:True,即逆時(shí)針。將值改為False即可改為順時(shí)針。
wedgeprops :字典類型,可選參數(shù),默認(rèn)值:None。參數(shù)字典傳遞給wedge對(duì)象用來(lái)畫一個(gè)餅圖。例如:wedgeprops={'linewidth':3}設(shè)置wedge線寬為3。
textprops :設(shè)置標(biāo)簽(labels)和比例文字的格式;字典類型,可選參數(shù),默認(rèn)值為:None。傳遞給text對(duì)象的字典參數(shù)。
center :浮點(diǎn)類型的列表,可選參數(shù),默認(rèn)值:(0,0)。圖標(biāo)中心位置。
frame :布爾類型,可選參數(shù),默認(rèn)值:False。如果是true,繪制帶有表的軸框架。
rotatelabels :布爾類型,可選參數(shù),默認(rèn)為:False。如果為True,旋轉(zhuǎn)每個(gè)label到指定的角度。
user_count = data[['casual','registered']].sum()
user_count
casual 392135
registered 1693341
dtype: int64
plt.figure(figsize=(8,6))
explode = [0.1,0]
labels = user_count.index
plt.pie(user_count,explode=explode,autopct='%.2f%%',labels=labels,pctdistance=1.3,labeldistance=0.5,)
# explode,距離圓中心的距離
# labels,(每一塊)餅圖外側(cè)顯示的說(shuō)明文字
# autopct在餅圖中,顯示百分?jǐn)?shù)
plt.title('餅圖',fontsize=18,pad=12)

面積圖 → plt.stackplot()
適用場(chǎng)景:強(qiáng)調(diào)數(shù)量隨時(shí)間而變化的程度,也可用于引起人們對(duì)總值趨勢(shì)的注意
data_stack = data.groupby('month').mean()[['casual','registered','count']]
x = data_stack.index
y = data_stack['casual']
y1 = data_stack['registered']
y2 = data_stack['count']
plt.figure(figsize=(12,6))
plt.stackplot(x,y,y1,y2,alpha=0.6,labels=data_stack.columns)
plt.xlim([1,12])
plt.title('面積圖',fontsize=18,pad=12)
plt.legend(loc=0)

散點(diǎn)圖 → plt.scatter(x,y)
適用場(chǎng)景:顯示若干數(shù)據(jù)系列中各數(shù)值之間的關(guān)系,類似XY軸,判斷兩變量之間是否存在某種關(guān)聯(lián)。散點(diǎn)圖適用于三維數(shù)據(jù)集,但其中只有兩維需要比較。
優(yōu)勢(shì):對(duì)于處理值的分布和數(shù)據(jù)點(diǎn)的分簇,散點(diǎn)圖都很理想。如果數(shù)據(jù)集中包含非常多的點(diǎn),那么散點(diǎn)圖便是最佳圖表類型。
劣勢(shì):在點(diǎn)狀圖中顯示多個(gè)序列看上去非?;靵y。
x = np.random.rand(1000)
y = np.random.randn(1000)*10
plt.figure(figsize=(8,6))
plt.scatter(x,y,color='r',alpha=0.5)
plt.title('散點(diǎn)圖',fontsize=18,pad=12)

散點(diǎn)圖延伸圖
氣泡圖 → plt.scatter(x,y,s)
氣泡圖:是可用于展示四個(gè)變量之間的關(guān)系。它與散點(diǎn)圖類似,繪制時(shí)將一個(gè)變量放在橫軸,另一個(gè)變量放在縱軸,而第三個(gè)變量則用氣泡的大小來(lái)表示,第四個(gè)變量用氣泡顏色深淺來(lái)表示。氣泡圖與散點(diǎn)圖相似,不同之處在于:氣泡圖允許在圖表中額外加入一個(gè)表示大小的變量進(jìn)行對(duì)比。
plt.scatter(x,y,s)的參數(shù):
x,y 輸入數(shù)據(jù)
s,用于調(diào)整點(diǎn)的大小,形成氣泡圖
c,用于調(diào)整顏色的深淺
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.figure(figsize=(12,8))
plt.scatter(x,y,s=np.random.randn(1000)*100,c=y,cmap='Blues',edgecolor='black',alpha=0.5)
plt.title('氣泡圖',fontsize=18,pad=12)

散點(diǎn)矩陣圖 → pd.scatter_matrix()
df = pd.DataFrame(np.random.randn(100,4),columns=list('ABCD'))
pd.scatter_matrix(df,figsize=(12,12),marker='o',diagonal='kde',range_padding=0.1)
# diagonal='hist' 設(shè)置對(duì)角線圖表形式,默認(rèn)直方圖hist,kde為密度圖
# range_padding=0.1,圖像在x軸、y軸原點(diǎn)附近的留白(padding),該值越大,留白距離越大,圖像遠(yuǎn)離坐標(biāo)原點(diǎn)

箱線圖 → plt.boxplot()/plt.plot.box()
箱型圖:是一種用作顯示一組數(shù)據(jù)分散情況資料的統(tǒng)計(jì)圖。主要用于反映原始數(shù)據(jù)分布的特征,還可以進(jìn)行多組數(shù)據(jù)分布特征的比較。箱線圖作用非常廣泛,可檢測(cè)異常值以及用于觀察數(shù)據(jù)形狀、偏態(tài)和尾重。
# plt.boxplot()
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
plt.figure(figsize=(10,4))
# 創(chuàng)建圖表、數(shù)據(jù)
f = df.boxplot(sym = 'o', # 異常點(diǎn)形狀,參考marker
vert = True, # 是否垂直
whis = 1.5, # IQR,默認(rèn)1.5,也可以設(shè)置區(qū)間比如[5,95],代表強(qiáng)制上下邊緣為數(shù)據(jù)95%和5%位置
patch_artist = True, # 上下四分位框內(nèi)是否填充,True為填充
meanline = False,showmeans=True, # 是否有均值線及其形狀
showbox = True, # 是否顯示箱線
showcaps = True, # 是否顯示邊緣線
showfliers = True, # 是否顯示異常值
notch = False, # 中間箱體是否缺口
return_type='dict' # 返回類型為字典
)
plt.title('箱線圖A',fontsize=18,pad=12)

# plt.boxplot()箱線圖分組匯總
season = data[['season','casual','registered']]
season.boxplot(by='season',figsize=(12,12),sym='+')

# plt.plot.box()
df.plot.box(figsize=(8,6),sym='+')
plt.title('箱線圖B',fontsize=18,pad=12)
