Matplotlib快速上手


Matplotlib → 一個python版的matlab繪圖接口,以2D爲主,支持python、numpy、pandas基本數據結構,運營高效且有較豐富的圖表庫

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 導入相關模塊

一、Matplotlib圖表各個部分詳解

在這裏插入圖片描述
title爲圖像標題,Axis爲座標軸, Label爲座標軸標註,Tick爲刻度線,Tick Label爲刻度註釋

在這裏插入圖片描述

二、圖表窗口

2.1 直接生成圖表 plt.show()

plt.plot(np.random.rand(10)) # 折線圖
plt.show()

在這裏插入圖片描述

2.2 魔法函數,嵌入圖表%matplotlib inline

					使用魔法函數後,就不用plt.show()也能顯示圖表了
			  魔法函數只有一種可以生效,運行完一個要使用另一個必須重啓程序
%matplotlib inline 
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y) #二維散點圖
# <matplotlib.collections.PathCollection at ...> 代表該圖表對象

在這裏插入圖片描述

2.3 魔法函數,彈出可交互的matplotlib窗口

								這種窗口可在繪圖後做一定調整與交互
%matplotlib notebook 
s = pd.Series(np.random.randn(100))
s.plot(style = 'k--o',figsize=(10,5))

在這裏插入圖片描述

2.4 魔法函數,彈出matplotlib控制檯

							控制檯的效果和matlab內的彈出窗口一樣
%matplotlib qt5
df = pd.DataFrame(np.random.rand(50,2),columns=['A','B'])
df.hist(figsize=(12,5),color='g',alpha=0.8) # 直方圖

在這裏插入圖片描述

2.5 關閉窗口和清空圖表內容

`#plt.close()    
# 關閉窗口

#plt.gcf().clear()  
# 清空圖表內內容`

三、圖表的基本元素

3.1圖名,圖例,軸標籤,軸邊界,軸刻度,軸刻度標籤等

df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])
fig = df.plot(figsize=(6,4))
# figsize:創建圖表窗口,設置窗口大小
# 創建圖表對象,並賦值與fig

plt.title('Interesting Graph - Check it out')  # 圖名
plt.xlabel('Plot Number')  # x軸標籤
plt.ylabel('Important var') # y軸標籤

plt.legend(loc = 'upper right')  
# 顯示圖例,loc表示位置
# 'best'         : 0, (only implemented for axes legends)(自適應方式)
# 'upper right'  : 1,
# 'upper left'   : 2,
# 'lower left'   : 3,
# 'lower right'  : 4,
# 'right'        : 5,
# 'center left'  : 6,
# 'center right' : 7,
# 'lower center' : 8,
# 'upper center' : 9,
# 'center'       : 10,

plt.xlim([0,12])  # x軸邊界(最小刻度到最大刻度的範圍)
plt.ylim([0,1.5])  # y軸邊界
plt.xticks(range(10))  # 設置x刻度
plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2])  # 設置y刻度

#刻度標籤應該與刻度一致
fig.set_xticklabels("%.1f" %i for i in range(10))  # x軸刻度標籤
fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2])  # y軸刻度標籤
# 範圍只限定圖表的長度,刻度則是決定顯示的標尺 → 這裏x軸範圍是0-12,但刻度只是0-9,刻度標籤使得其顯示1位小數
# 軸標籤則是顯示刻度的標籤

print(fig,type(fig))
# 查看錶格本身的顯示方式,以及類別

3.2 網格、刻度、註釋參數設置

# 其他元素可視性

# 通過ndarry創建圖表
x = np.linspace(-np.pi,np.pi,256,endpoint = True)
c, s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)


# 顯示網格
# linestyle:線型
# color:顏色
# linewidth:寬度
# axis:x,y,both,顯示x/y/兩者的格網
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')  


# 刻度顯示
plt.tick_params(bottom='on',top='off',left='on',right='off')  


# 設置刻度的方向,in,out,inout 
# 這裏需要導入matploltib,而不僅僅導入matplotlib.pyplot
import matplotlib
matplotlib.rcParams['xtick.direction'] = 'out' 
matplotlib.rcParams['ytick.direction'] = 'inout' 



frame = plt.gca()# 獲取當前子圖
# 關閉座標軸
#plt.axis('off')
# x/y 軸不可見
#frame.axes.get_xaxis().set_visible(False)
#frame.axes.get_yaxis().set_visible(False)

在這裏插入圖片描述

						刻度方向就是刻度是否凸出圖標邊框這部分
# 註解

df = pd.DataFrame(np.random.randn(10,2))
df.plot(style = '--o')
plt.text(5,0.5,'hahaha',fontsize=10)  
# 註解 → 橫座標,縱座標,註解字符串

3.3 線型 linestyle

plt.plot([i**2 for i in range(100)],
        linestyle = '-.',linewidth=0.5)
# '-'       solid line style
# '--'      dashed line style
# '-.'      dash-dot line style
# ':'       dotted line style

在這裏插入圖片描述

3.4 點型 marker

s = pd.Series(np.random.randn(100).cumsum())
s.plot(linestyle = '--',
      marker = 'x')
# '.'       point marker
# ','       pixel marker
# 'o'       circle marker
# 'v'       triangle_down marker
# '^'       triangle_up marker
# '<'       triangle_left marker
# '>'       triangle_right marker
# '1'       tri_down marker
# '2'       tri_up marker
# '3'       tri_left marker
# '4'       tri_right marker
# 's'       square marker
# 'p'       pentagon marker
# '*'       star marker
# 'h'       hexagon1 marker
# 'H'       hexagon2 marker
# '+'       plus marker
# 'x'       x marker
# 'D'       diamond marker
# 'd'       thin_diamond marker
# '|'       vline marker
# '_'       hline marker

在這裏插入圖片描述

3.5 color參數

plt.hist(np.random.randn(100),
        color = 'g',alpha = 0.8)
# alpha:0-1,透明度
# 常用顏色簡寫:red-r, green-g, black-k, blue-b, yellow-y

df = pd.DataFrame(np.random.randn(1000, 4),columns=list('ABCD'))
df = df.cumsum()
df.plot(style = '--.',alpha = 0.8,colormap = 'GnBu')
# colormap:顏色板,包括:
# Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r,
# Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, 
# PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, 
# RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, 
# YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, 
# cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r,
# gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, 
# gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, hsv_r, inferno, inferno_r, jet, jet_r, magma, magma_r, nipy_spectral, 
# nipy_spectral_r, ocean, ocean_r, pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, seismic, seismic_r, spectral, 
# spectral_r ,spring, spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, winter, winter_r

詳細參數見:https://download.csdn.net/download/qq_34213260/12534748

3.6 style參數,相當於包含linestyle,marker,color

ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))
ts.plot(style = '--g.',grid = True)
# style → 風格字符串,這裏包括了linestyle(-),color(g),marker(.)

3.7 整體風格樣式

import matplotlib.style as psl
print(plt.style.available)# 查看樣式列表

psl.use('ggplot')
ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))
ts.plot(style = '--g.',grid = True,figsize=(10,6))


# 一旦選用樣式後,所有圖表都會有樣式,重啓後才能關掉

四、子圖

在matplotlib中,整個圖像爲一個Figure對象。在Figure對象中可以包含一個或者多個Axes對象。每個Axes(ax)對象都是一個擁有自己座標系統的繪圖區域
plt.figure, plt.subplot

4.1 子圖創建

  • 方法一
# 子圖創建1 - 先建立子圖然後填充圖表

fig = plt.figure(figsize=(10,6),facecolor = 'gray')

ax1 = fig.add_subplot(2,2,1)  # 第一行的左圖
plt.plot(np.random.rand(50).cumsum(),'k--')
plt.plot(np.random.randn(50).cumsum(),'b--')
# 先創建圖表figure,然後生成子圖,(2,2,1)代表創建2*2的矩陣表格,然後選擇第一個,順序是從左到右從上到下
# 創建子圖後繪製圖表,會繪製到最後一個子圖

# 也可以直接在子圖後用圖表創建函數直接生成圖表
ax2 = fig.add_subplot(2,2,2)  # 第一行的右圖
ax2.hist(np.random.rand(50),alpha=0.5)

ax4 = fig.add_subplot(2,2,4)  # 第二行的右圖
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')

在這裏插入圖片描述

  • 方法二
# 子圖創建2 - 創建一個新的figure,並返回一個subplot對象的numpy數組 → plt.subplot

fig,axes = plt.subplots(2,3,figsize=(10,4))
ts = pd.Series(np.random.randn(1000).cumsum())
print(axes, axes.shape, type(axes))
# 生成圖表對象的數組

ax1 = axes[0,1]
ax1.plot(ts)
df = pd.DataFrame(np.random.rand(100,2))
df.plot(ax=axes[1,1])

在這裏插入圖片描述

4.2 plt.subplots子圖參數調整

# plt.subplots,參數調整

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
# sharex,sharey:是否共享x,y刻度

for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
# wspace,hspace:用於控制子圖間隔的寬度和高度的百分比,比如subplot之間的間距

五、基本圖標類型繪製

圖表類別:線形圖、柱狀圖、密度圖,以橫縱座標兩個維度爲主

同時可延展出多種其他圖表樣式

plt.plot(kind='line', ax=None, figsize=None, use_index=True, title=None, grid=None, 
legend=False, style=None, logx=False, logy=False, loglog=False, xticks=None, yticks=None, 
xlim=None, ylim=None,  rot=None, fontsize=None, colormap=None, table=False, yerr=None, 
xerr=None, label=None, secondary_y=False, **kwds)

默認是折線圖

5.1 Series直接生成圖表

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot(kind='line',
       label = 'hehe',
       style = '--g.',
       color = 'red',
       alpha = 0.4,
       use_index = True,
       rot = 45,
       grid = True,
       ylim = [-50,50],
       yticks = list(range(-50,50,10)),
       figsize = (8,4),
       title = 'test',
       legend = True)
#plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'x')  # 網格
plt.legend()
# Series.plot():series的index爲橫座標,value爲縱座標
# kind → line,bar,barh...(折線圖,柱狀圖,柱狀圖-橫...)
# label → 圖例標籤,Dataframe格式以列名爲label
# style → 風格字符串,這裏包括了linestyle(-),marker(.),color(g)
# color → 顏色,有color指定時候,以color顏色爲準
# alpha → 透明度,0-1
# use_index → 將索引用爲刻度標籤,默認爲True
# rot → 旋轉刻度標籤,0-360
# grid → 顯示網格,一般直接用plt.grid
# xlim,ylim → x,y軸界限
# xticks,yticks → x,y軸刻度值
# figsize → 圖像大小
# title → 圖名
# legend → 是否顯示圖例,一般直接用plt.legend()
# 也可以 → plt.plot()

在這裏插入圖片描述

5.2 Dataframe直接生成圖表

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(kind='line',
       style = '--.',
       alpha = 0.4,
       use_index = True,
       rot = 45,
       grid = True,
       figsize = (8,4),
       title = 'test',
       legend = True,
       subplots = False,
       colormap = 'Greens')
# subplots → 是否將各個列繪製到不同圖表,默認False
# 也可以 → plt.plot(df)

在這裏插入圖片描述

5.3 柱狀圖與堆疊圖

fig,axes = plt.subplots(4,1,figsize = (10,10))
s = pd.Series(np.random.randint(0,10,16),index = list('abcdefghijklmnop'))  
df = pd.DataFrame(np.random.rand(10,3), columns=['a','b','c'])

s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0])  # ax參數 → 選擇第幾個子圖
# 單系列柱狀圖方法一:plt.plot(kind='bar/barh')

df.plot(kind='bar',ax = axes[1],grid = True,colormap='Reds_r')
# 多系列柱狀圖

df.plot(kind='bar',ax = axes[2],grid = True,colormap='Blues_r',stacked=True) 
# 多系列堆疊圖
# stacked → 堆疊

df.plot.barh(ax = axes[3],grid = True,stacked=True,colormap = 'BuGn_r')
# 新版本plt.plot.<kind>

在這裏插入圖片描述

plt.figure(figsize=(10,4))
x = np.arange(10)
y1 = np.random.rand(10)
y2 = -np.random.rand(10)

plt.bar(x,y1,width = 1,facecolor = 'yellowgreen',edgecolor = 'white',yerr = y1*0.1)
plt.bar(x,y2,width = 1,facecolor = 'lightskyblue',edgecolor = 'white',yerr = y2*0.1)
# x,y參數:x,y值
# width:寬度比例
# facecolor柱狀圖裏填充的顏色、edgecolor是邊框的顏色
# left-每個柱x軸左邊界,bottom-每個柱y軸下邊界 → bottom擴展即可化爲甘特圖 Gantt Chart
# align:決定整個bar圖分佈,默認left表示默認從左邊界開始繪製,center會將圖繪製在中間位置
# xerr/yerr :x/y方向error bar

for i,j in zip(x,y1):
    plt.text(i+0.3,j-0.15,'%.2f' % j, color = 'white')
for i,j in zip(x,y2):
    plt.text(i+0.3,j+0.05,'%.2f' % -j, color = 'white')
# 給圖添加text
# zip() 函數用於將可迭代的對象作爲參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。

在這裏插入圖片描述

5.4 面積圖

fig,axes = plt.subplots(2,1,figsize = (8,6))
df1 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])

df1.plot.area(colormap = 'Greens_r',alpha = 0.5,ax = axes[0])
df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])
# 使用Series.plot.area()和DataFrame.plot.area()創建面積圖
# stacked:是否堆疊,默認情況下,區域圖被堆疊
# 爲了產生堆積面積圖,每列必須是正值或全部負值!
# 當數據有NaN時候,自動填充0,所以圖標籤需要清洗掉缺失值

在這裏插入圖片描述

5.5 填圖

fig,axes = plt.subplots(2,1,figsize = (8,6))

x = np.linspace(0, 1, 500)
y1 = np.sin(4 * np.pi * x) * np.exp(-5 * x)
y2 = -np.sin(4 * np.pi * x) * np.exp(-5 * x)
axes[0].fill(x, y1, 'r',alpha=0.5,label='y1')
axes[0].fill(x, y2, 'g',alpha=0.5,label='y2')
# 對函數與座標軸之間的區域進行填充,使用fill函數
# 也可寫成:plt.fill(x, y1, 'r',x, y2, 'g',alpha=0.5)

x = np.linspace(0, 5 * np.pi, 1000) 
y1 = np.sin(x)  
y2 = np.sin(2 * x)  
axes[1].fill_between(x, y1, y2, color ='b',alpha=0.5,label='area')  
# 填充兩個函數之間的區域,使用fill_between函數

for i in range(2):
    axes[i].legend()
    axes[i].grid()
# 添加圖例、格網

在這裏插入圖片描述

5.6 餅圖 plt.pie()

# plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, 
# radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, hold=None, data=None)

s = pd.Series(3 * np.random.rand(4), index=['a', 'b', 'c', 'd'], name='series')
plt.axis('equal')  # 保證長寬相等
plt.pie(s,
       explode = [0.1,0,0,0],
       labels = s.index,
       colors=['r', 'g', 'b', 'c'],
       autopct='%.2f%%',
       pctdistance=0.6,
       labeldistance = 1.2,
       shadow = True,
       startangle=0,
       radius=1.5,
       frame=False)
print(s)
# 第一個參數:數據
# explode:指定每部分的偏移量
# labels:標籤
# colors:顏色
# autopct:餅圖上的數據標籤顯示方式
# pctdistance:每個餅切片的中心和通過autopct生成的文本開始之間的比例
# labeldistance:被畫餅標記的直徑,默認值:1.1
# shadow:陰影
# startangle:開始角度
# radius:半徑
# frame:圖框
# counterclock:指定指針方向,順時針或者逆時針

在這裏插入圖片描述

5.7 直方圖+密度圖

s = pd.Series(np.random.randn(1000))
s.hist(bins = 20,
       histtype = 'bar',
       align = 'mid',
       orientation = 'vertical',
       alpha=0.5,
       normed =True)
# bin:箱子的寬度
# normed 標準化
# histtype 風格,bar,barstacked,step,stepfilled
# orientation 水平還是垂直{‘horizontal’, ‘vertical’}
# align : {‘left’, ‘mid’, ‘right’}, optional(對齊方式)

s.plot(kind='kde',style='k--')
# 密度圖

在這裏插入圖片描述

5.8 堆疊直方圖

plt.figure(num=1)
df = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000),
                    'c': np.random.randn(1000) - 1, 'd': np.random.randn(1000)-2},
                   columns=['a', 'b', 'c','d'])
df.plot.hist(stacked=True,
             bins=20,
             colormap='Greens_r',
             alpha=0.5,
             grid=True)
# 使用DataFrame.plot.hist()和Series.plot.hist()方法繪製
# stacked:是否堆疊

df.hist(bins=50)
# 生成多個直方圖

在這裏插入圖片描述

5.9 plt.scatter()散點圖

# plt.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None, 
# alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)

plt.figure(figsize=(8,6))
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y,marker='.',
           s = np.random.randn(1000)*100,
           cmap = 'Reds',
           c = y,
           alpha = 0.8,)
plt.grid()
# s:散點的大小
# c:散點的顏色
# vmin,vmax:亮度設置,標量
# cmap:colormap

在這裏插入圖片描述

5.10 pd.scatter_matrix()散點矩陣

# pd.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, 
# grid=False, diagonal='hist', marker='.', density_kwds=None, hist_kwds=None, range_padding=0.05, **kwds)

df = pd.DataFrame(np.random.randn(100,4),columns = ['a','b','c','d'])
pd.scatter_matrix(df,figsize=(10,6),
                 marker = 'o',
                 diagonal='kde',
                 alpha = 0.5,
                 range_padding=0.1)
# diagonal:({‘hist’, ‘kde’}),必須且只能在{‘hist’, ‘kde’}中選擇1個 → 每個指標的頻率圖
# range_padding:(float, 可選),圖像在x軸、y軸原點附近的留白(padding),該值越大,留白距離越大,圖像遠離座標原點

在這裏插入圖片描述

5.11 箱型圖

  • 方法1
# plt.plot.box()繪製

fig,axes = plt.subplots(2,1,figsize=(10,6))
df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
color = dict(boxes='DarkGreen', whiskers='DarkOrange', medians='DarkBlue', caps='Gray')
# 箱型圖着色
# boxes → 箱線
# whiskers → 分位數與error bar橫線之間豎線的顏色
# medians → 中位數線顏色
# caps → error bar橫線顏色

df.plot.box(ylim=[0,1.2],
           grid = True,
           color = color,
           ax = axes[0])
# color:樣式填充

df.plot.box(vert=False, 
            positions=[1, 4, 5, 6, 8],
            ax = axes[1],
            grid = True,
           color = color)
# vert:是否垂直,默認True
# position:箱型圖佔位

在這裏插入圖片描述

  • 方法2
# plt.boxplot()繪製
# pltboxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, 
# usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, 
# labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_xticks=True, autorange=False, 
# zorder=None, hold=None, data=None)

df = pd.DataFrame(np.random.rand(10, 5), columns=['A', 'B', 'C', 'D', 'E'])
plt.figure(figsize=(10,4))
# 創建圖表、數據

f = df.boxplot(sym = 'o',  # 異常點形狀,參考marker
               vert = True,  # 是否垂直
               whis = 1.5,  # IQR,默認1.5,也可以設置區間比如[5,95],代表強制上下邊緣爲數據95%和5%位置
               patch_artist = True,  # 上下四分位框內是否填充,True爲填充
               meanline = False,showmeans=True,  # 是否有均值線及其形狀
               showbox = True,  # 是否顯示箱線
               showcaps = True,  # 是否顯示邊緣線
               showfliers = True,  # 是否顯示異常值
               notch = False,  # 中間箱體是否缺口
               return_type='dict'  # 返回類型爲字典
              ) 
plt.title('boxplot')
print(f)

for box in f['boxes']:
    box.set( color='b', linewidth=1)        # 箱體邊框顏色
    box.set( facecolor = 'b' ,alpha=0.5)    # 箱體內部填充顏色
for whisker in f['whiskers']:
    whisker.set(color='k', linewidth=0.5,linestyle='-')
for cap in f['caps']:
    cap.set(color='gray', linewidth=2)
for median in f['medians']:
    median.set(color='DarkBlue', linewidth=2)
for flier in f['fliers']:
    flier.set(marker='o', color='y', alpha=0.5)
# boxes, 箱線
# medians, 中位值的橫線,
# whiskers, 從box到error bar之間的豎線.
# fliers, 異常值
# caps, error bar橫線
# means, 均值的橫線,

在這裏插入圖片描述

  • 方法3
# plt.boxplot()繪製
# 分組彙總

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'])
df['Y'] = pd.Series(['A','B','A','B','A','B','A','B','A','B'])
print(df.head())
df.boxplot(by = 'X')
df.boxplot(column=['Col1','Col2'], by=['X','Y'])
# columns:按照數據的列分子圖
# by:按照列分組做箱型圖

在這裏插入圖片描述

六、圖表保存輸出

plt.savefig('C:/Users/iHJX_Alienware/Desktop/pic.png',
            dpi=400,
            bbox_inches = 'tight',
            facecolor = 'g',
            edgecolor = 'b')
# 可支持png,pdf,svg,ps,eps…等,以後綴名來指定
# dpi是像素分辨率
# bbox_inches:圖表需要保存的部分。如果設置爲‘tight’,則嘗試剪除圖表周圍的空白部分。
# facecolor,edgecolor: 圖像的背景色,默認爲‘w’(白色)

打賞

碼字不易,如果對您有幫助,就打賞一下吧O(∩_∩)O

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章