安利 5 個拍案叫絕的 Matplotlib 騷操做!

公衆號:Python數據科學
做者:東哥起飛

你們都知道,Matplotlib是Python的可視化庫,功能很強,能夠繪製各類圖。一些常規用法前不久分享過Matplotlib官方出品的cheatsheet:Matplotlib官方小抄手冊公開,配套可視化代碼已打包!python

可是!今天咱們不走尋常路,專挑幾個賊騷的操做分享下.git

1. Span Selector

Span SelectorMatplotlib中的鼠標小部件,widgets是用於包含一些交互功能的python對象。Span Selector能夠經過鼠標框選,方便地查看選定區域的最大值和最小值。github

下面是代碼,首先建立一個基本折線圖做爲例子。而後,咱們調用SpanSelector方法並使用它來選擇一個區域,而後在該區域中顯示最大值和最小值。算法

import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
def onselect(xmin, xmax):
    print(xmin, xmax)
    return xmin, xmax
fig, ax = plt.subplots()
ax.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45])
span = SpanSelector(ax, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red'))       
plt.show()

下面是具體操做。
image微信

2. Broken Barh

Broken的水平條形圖是不連續具備間隙的圖,它可用於數據值相差很大的狀況下,例如,包含極端溫度範圍的數據集。在這種狀況下,Broken的水平條形圖很是合適,由於它們能夠同時繪製最大和最小範圍。app

python模塊matplotlib.broken_barh()用於繪製Broken的水平條形圖。dom

import matplotlib.pyplot as plt 
#Defining the x and y ranges 
xranges = [(5,5), (20,5),(20,7)] 
yrange = (2,1) 
#Plotting the broken bar chart 
plt.broken_barh(xranges, yrange, facecolors='green') 
xranges = [(6,2), (17,5),(50,2)] 
yrange = (15,1) 
plt.broken_barh(xranges, yrange, facecolors='orange') 
xranges = [(5,2), (28,5),(40,2)] 
yrange = (30,1) 
plt.broken_barh(xranges, yrange, facecolors='red') 
plt.xlabel('Sales') 
plt.ylabel('Days of the Month') 
plt.show()

image

3. Table Demo

Matplotlib的表格功能也是能夠在圖中顯示錶格的。當咱們但願以條形圖的形式快速查看錶格中的值時,這特別方便。表格能夠放置在圖表的頂部,底部或側面。機器學習

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
x = np.random.rand(5, 8)*.7 
plt.plot(x.mean(axis=0), '-o', label='average per column') 
plt.xticks([]) 
plt.table(cellText=[['%1.2f' % xxx for xxx in xx] for xx in x],cellColours=plt.cm.GnBu(x),loc='bottom') 
plt.show()

image
image

4. Watermark Images

有時候咱們以爲可視化的背景太單調了,想增長點趣味性,好比將與數據相關的圖像做爲水印覆蓋到可視化圖形上。下面就以NBA的詹皇爲例試試水,最後呈現出詹皇的數據,同時背景是詹皇本人。學習

首先,導入要用的數據集,圖片和必要的庫pandasspa

import numpy as np 
import matplotlib.image as image 
import matplotlib.pyplot as plt 
import pandas as pd 
df = pd.read_csv('income.csv') 
im = image.imread('Lebron_James.jpeg') # Image

pandas過濾掉僅由勒布朗組成的數據。

lebron_james = df[df['Name']=='LeBron James']

而後像下面這樣操做,使用figimage添加水印就ok了。

fig, ax = plt.subplots() 
ax.grid() 
ax.plot('Year','earnings ($ million)',data=lebron_james) 
ax.set_title("LeBron James earnings in US$(millions)") 
fig.figimage(im, 60, 40,cmap='ocean', alpha=.2) 
plt.show()

image

5. XKCD Plots

下面這個操做更有趣味性(更騷)。

若是你想讓Matplotlib圖上添加一些扭曲,能夠簡單地xkcd()pyplot對象上調用方法,以下所示。

import pandas as pd 
import matplotlib.pyplot as plt 
df = pd.read_csv('https://raw.githubusercontent.com/parulnith/Website-articles-datasets/master/India%20GDP%20Growth%20Rate%20.csv', parse_dates=['Year']) 
df['Year'] = df['Year'].apply(lambda x: pd.Timestamp(x).strftime('%Y')) 
#calling xkcd() method 
plt.xkcd(scale=5, length=400) 
df.plot(x='Year',y='GDP Growth (%)',kind='bar') 
plt.ylabel('GDP Growth (%)') 
plt.xticks(rotation=-20) 
plt.figure(figsize=(10,8)) 
plt.show()

image

文章參考:
https://towardsdatascience.co...

先分享這些,若是以爲有幫助,還請多分享點個贊

歡迎你們關注個人原創微信公衆號 Python數據科學,專一於寫基於Python的數據算法、機器學習、深度學習硬核乾貨。

相關文章
相關標籤/搜索