一文搞定Matplotlib快速入門

# 導入模塊
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

1 柱狀圖與堆疊圖

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

# 單系列柱狀圖
s.plot(kind='bar',color = 'k',grid = True,alpha = 0.5,ax = axes[0])
# 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()
# ax參數 → 選擇第幾個子圖

# 多系列柱狀圖
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)

在這裏插入圖片描述

2 面積圖

fig,axes = plt.subplots(2,1,figsize = (10,10))
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])
plt.legend(loc='upper right')
df2.plot.area(stacked=False,colormap = 'Set2',alpha = 0.5,ax = axes[1])

在這裏插入圖片描述

3 餅圖

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], # explode:指定每部分的偏移量
        labels = s.index, # labels:標籤
        colors=['r', 'g', 'b', 'c'], # colors:顏色
        autopct='%.2f%%', # autopct:餅圖上的數據標籤顯示方式
        pctdistance=0.6,  # pctdistance:每個餅切片的中心和通過autopct生成的文本開始之間的比例
        labeldistance = 1.2, # labeldistance:被畫餅標記的直徑,默認值:1.1
        shadow = True, # shadow:陰影
        startangle=0, # startangle:開始角度
        radius=1.5, # radius:半徑
        frame=False) # frame:圖框

在這裏插入圖片描述

4 直方圖+密度圖

s = pd.Series(np.random.randn(1000))

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

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

在這裏插入圖片描述

5 堆疊直方圖

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, # stacked:是否堆疊
              bins=20,
              colormap='Greens_r',
              alpha=0.5,
              grid=True)

在這裏插入圖片描述

6 散點圖

x = np.random.randn(1000)
y = np.random.randn(1000)

plt.scatter(x,y,marker='.',
            s = np.random.randn(1000)*100, # s:散點的大小
            cmap = 'Reds',  # cmap:colormap
            c = y, # c:散點的顏色
            alpha = 0.8,)

在這裏插入圖片描述

7 箱型圖

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, # color:樣式填充
            ax = axes[0])

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

在這裏插入圖片描述

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