關於matplotlib,你要的餅圖在這裡

2021-03-02 Python數據之道

Table of Contents

1  官方Demo

2  將實際數據應用於官方Demo

3  一些改善措施

3.1  重新設置字體大小

3.2  設置顯示顏色,Method 1:

3.3  設置顯示顏色, Method 2:

3.4  設置圖例(legend)

3.5  重新設置圖例(legend)

3.6  將某些類別突出顯示

# 前言

matplotlib, 官方提供的餅圖Demo,功能比較比較簡單,在實際應用過程中,往往會有許多個性化的繪製需求,在這裡跟大家一起了解下餅圖(pie chart)的一些特色的功能的實現。

from matplotlib import font_manager as fm

import matplotlib as mpl

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

% matplotlib inline

plt.style.use('ggplot')

1. 官方Demo

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()

ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',

       shadow=True, startangle=90)

ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.savefig('Demo_official.jpg')

plt.show()

2. 將實際數據應用於官方Demo

# 原始數據

shapes = ['Cross', 'Cone', 'Egg', 'Teardrop', 'Chevron', 'Diamond', 'Cylinder',

      'Rectangle', 'Flash', 'Cigar', 'Changing', 'Formation', 'Oval', 'Disk',

      'Sphere', 'Fireball', 'Triangle', 'Circle', 'Light']

values = [  287,   383,   842,   866,  1187,  1405,  1495,  1620,  1717,

       2313,  2378,  3070,  4332,  5841,  6482,  7785,  9358,  9818, 20254]

s = pd.Series(values, index=shapes)

s

from matplotlib import font_manager as fm

import matplotlib as mpl

# Pie chart, where the slices will be ordered and plotted counter-clockwise:

labels = s.index

sizes = s.values

explode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig1, ax1 = plt.subplots()

patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170)

ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.savefig('Demo_project.jpg')

plt.show()


上圖的一些問題:

顏色比較生硬

部分文字擁擠在一起,繪圖顯示不齊整

3. 一些改善措施

重新設置字體大小

設置自選顏色

設置圖例

將某些類別突出顯示

3.1 重新設置字體大小

from matplotlib import font_manager as fm

import matplotlib as mpl

labels = s.index

sizes = s.values

explode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig1, ax1 = plt.subplots()

patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170)

ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

plt.savefig('Demo_project_set_font.jpg')

plt.show()

3.2 設置顯示顏色,Method 1:

from matplotlib import font_manager as fm

import matplotlib as mpl

# Pie chart, where the slices will be ordered and plotted counter-clockwise:

labels = s.index

sizes = s.values

explode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig1, ax1 = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小

a = np.random.rand(1,19)

color_vals = list(a[0])

my_norm = mpl.colors.Normalize(-1, 1) # 將顏色數據的範圍設置為 [0, 1]

my_cmap = mpl.cm.get_cmap('rainbow', len(color_vals)) # 可選擇合適的colormap,如:'rainbow'

patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170, colors=my_cmap(my_norm(color_vals)))

ax1.axis('equal')  

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

plt.savefig('Demo_project_set_color_1.jpg')

plt.show()

上面這種方法設置顏色時,但類別比較多時,部分顏色的填充會重複。

有時候,我們可能想設置成連續的顏色,可以有另外一種方法來實現。

3.3 設置顯示顏色, Method 2:

from matplotlib import font_manager as fm

from  matplotlib import cm

labels = s.index

sizes = s.values

# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig, ax = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小

colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks

patches, texts, autotexts = ax.pie(sizes, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170, colors=colors)

ax.axis('equal')  

ax.set_title('Shapes ----', loc='left')

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

plt.savefig('Demo_project_set_color_2.jpg')

plt.show()

從上圖可以看出,顏色顯示是連續的,實現了我們想要的效果

3.4 設置圖例(legend)

from matplotlib import font_manager as fm

from  matplotlib import cm

labels = s.index

sizes = s.values

# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig, ax = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小

colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks

patches, texts, autotexts = ax.pie(sizes, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170, colors=colors)

ax.axis('equal')  

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

ax.legend(labels, loc=2)

plt.savefig('Demo_project_set_legend_error.jpg')

plt.show()

從上面可看出,當類別較多時,圖例(legend)的位置擺放顯示有重疊,顯示有些問題,需要進行調整。

3.5 重新設置圖例(legend)

from matplotlib import font_manager as fm

from  matplotlib import cm

labels = s.index

sizes = s.values

# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)  # only "explode" the 1st slice

fig, axes = plt.subplots(figsize=(10,5),ncols=2) # 設置繪圖區域大小

ax1, ax2 = axes.ravel()

colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks

patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%',

       shadow=False, startangle=170, colors=colors)

ax1.axis('equal')  

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

ax1.set_title('Shapes', loc='center')

# ax2 只顯示圖例(legend)

ax2.axis('off')

ax2.legend(patches, labels, loc='center left')

plt.tight_layout()

plt.savefig('Demo_project_set_legend_good.jpg')

plt.show()

3.6 將某些類別突出顯示

將某些類別突出顯示

控制label的顯示位置

控制百分比的顯示位置

控制突出位置的大小

from matplotlib import font_manager as fm

from  matplotlib import cm

labels = s.index

sizes = s.values

explode = (0.1,0,0,0,0,0,0,0,0,0,0,0,0,0.2,0,0,0,0.1,0)  # "explode" , show the selected slice

fig, axes = plt.subplots(figsize=(8,5),ncols=2) # 設置繪圖區域大小

ax1, ax2 = axes.ravel()

colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks

patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%',explode=explode,

       shadow=False, startangle=170, colors=colors, labeldistance=1.2,pctdistance=1.03, radius=0.4)

# labeldistance: 控制labels顯示的位置

# pctdistance: 控制百分比顯示的位置

# radius: 控制切片突出的距離

ax1.axis('equal')  

# 重新設置字體大小

proptease = fm.FontProperties()

proptease.set_size('xx-small')

# font size include: 『xx-small』,x-small』,'small』,'medium』,『large』,『x-large』,『xx-large』 or number, e.g. '12'

plt.setp(autotexts, fontproperties=proptease)

plt.setp(texts, fontproperties=proptease)

ax1.set_title('Shapes', loc='center')

# ax2 只顯示圖例(legend)

ax2.axis('off')

ax2.legend(patches, labels, loc='center left')

plt.tight_layout()

# plt.savefig("pie_shape_ufo.png", bbox_inches='tight')

plt.savefig('Demo_project_final.jpg')

plt.show()

更多精彩內容請關注公眾號:

「Python數據之道」

相關焦點

  • Matplotlib數據可視化:餅圖與箱線圖
    from matplotlib import pyplot as pltimport numpy as npimport matplotlib as mplmpl.rcParams['font.sans-serif'] = ['SimHei']  # 中文字體支持1 餅圖-pie()1.1 pie
  • Matplotlib圖鑑|基礎餅圖
    首先導入相關庫並查看版本import matplotlibprint(matplotlib.__version__) #查看Matplotlib版本import pandas as pdprint(pd.
  • python使用matplotlib畫動態圖
    matplotlib是python的核心繪圖庫,是python的一個開源項目,旨在為python提供一個繪圖庫。matplotlib與numpy組合是一種可行的matlab替代方案。在可視化中matplotlib是最常使用的工具,是對數據整體判斷、效果預測不可或缺的重要模塊。下面我們就來聊一聊如何使用matplotlib繪製一個二維動態圖。
  • matplotlib繪圖的核心原理講解
    作者:朱小五來自:凹凸數據(ID:alltodata)matplotlib是基於Python語言的開源項目,旨在為Python提供一個數據繪圖包。相信大家都用過它來數據可視化,之前我還分享過25個常用Matplotlib圖的Python代碼。可是你了解過它繪圖的核心原理嗎?
  • Python-matplotlib 多子圖共用colorbar
    matplotlib 繪製教程後,有小夥伴反應能否出一篇多子圖共用一個colorbar的系列教程,這裡也就使用自己的數據進行繪製(數據一共四列,具體為真實值和使用三個模型計算的預測值)。在繪製多子圖共用colorbar時,最重要的就是對顏色映射進行設置,這裡使用了matplotlib.color.Normalize()進行顏色和數值對應設置。先看一下使用默認設置的結果,每個子圖對應一個colorbar。
  • matplotlib中文顯示之圖表大全
    全局支持中文顯示以及指定局部中文顯示https://aistudio.baidu.com/aistudio/projectdetail/390895使用中還有問題可以在論壇中提出(你的問題可能大家已經討論過了)https://ai.baidu.com/forum/topic/show/958873考慮到部分同學對matplotlib本身不是太熟悉
  • python可視化之matplotlib庫餅形圖的基本用法與應用實例
    實驗環境:已正確安裝python3.5、matplotlib1、餅形圖概念餅狀圖顯示一個整體中各項大小佔總體的百分比,可以清楚反應部分與總體的關係。在餅形圖上標出百分比為了在平面上觀察各項的比例,可以設置x與y的比例為1進行觀察。利用axes方法創建或激活軸,aspect為一個數字時,表示屏幕空間中y與x之比。
  • Python-Matplotlib: 極坐標圖形
    風玫瑰圖風玫瑰圖就是極坐標系下的堆積分組柱形圖, 這裡定義1個函數,返回繪圖對象和刻度坐標及標籤。使用時,提取刻度坐標和標籤就行了,繪圖對象使用_進行列印。山巒圖使用fill_between()方法即可繪製單個填充區域,這裡定義1個函數繪製山巒圖,可以自動扣除基線, 手動進行縱坐標基線偏移。
  • Matplotlib的安裝與繪圖
    就是繪圖的主要工具 Matplotlib的安裝 pip --default-time=10000 install matplotlib繪製簡單的曲線 import matplotlib.pyplot as plt#簡單的曲線plt.plot([1,2,3
  • Matplotlib可視化菜鳥教程
    散點圖、折線圖、柱狀圖、條形圖、餅圖、直方圖是非常常用而基礎的可視化圖。個人認為通過畫這幾種基礎圖並調細節是很好的學可視化實踐。用同一列數據繪製的直方圖與箱線圖餅圖是可視化中基礎而重要的圖形,是各種數據報告的常客,Matplotlib繪製餅圖時因為xy軸默認比例尺不同,為了得到不扁的餅,需設置xy軸1像素對應的值相等。
  • python數據分析【三】matplotlib常用圖案例
    python是一個包容性、開放性很強的語言,因此matplotlib模塊亦是如此,例如上面的兔子便是以python 畫的。你可以隨心所欲的在上面塗塗畫畫,如果你的審美比較與眾不同,你也可以使用像R語言的ggplot2的畫圖風格。本文將介紹一些簡便常用的圖形並對應介紹它可以使用的場景。
  • Matplotlib--上帝打翻了調色板
    同樣在圖形中,我們也可以運用matplotlib工具包,繪製斑斕的圖像。此次本文將從matplotlib的繪圖樣式和色彩設置兩個方面來對圖像的形式講解,重點在於色彩的應用。Matplotlib的繪圖樣式(style)在Matplotlib中,要想設置繪製樣式,最簡單的方法是在繪製元素時單獨設置樣式。
  • 基於Python的圖表繪圖系統matplotlib,「餅圖「「你真了解嗎?
    按照國際慣例,寫在最開始的是對要介紹對象的定義。喏,這是從維基百科搬運過來的對餅圖的解釋,請安心受下:餅圖,或稱餅狀圖,是一個劃分為幾個扇形的圓形統計圖表,用於描述量、頻率或百分比之間的相對關係。在餅圖中,每個扇區的弧長(以及圓心角和面積)大小為其所表示的數量的比例。
  • Python Matplotlib 入門教程:如何控制Matplotlib樣式
    來自:https://www.linuxmi.com/matplotlib-yangshi.html在本篇Python Matplotlib
  • PyCharm安裝matplotlib教程——安裝好matplotlib但是import報錯
    輸入python -m pip install -U pip setuptools2.輸入python -m pip install matplotlib3.檢查是否已經安裝成功默認安裝在D:\Python\Lib\site-packages方式二:通過下載matplotlib進行安裝。進入matplotlib官網。
  • 創造生動有趣的動畫,Matplotlib庫大顯身手
    在描述像過去幾年的股票價格、過去十年的氣候變化、季節性和趨勢等時間序列數據時,與靜態圖相比,動畫更能說明問題。因為,從動畫中,我們可以看到特定參數是如何隨時間而變化的。上圖是模擬雨的圖像。此圖由Matplotlib繪圖庫繪製而成,該繪圖庫常常被認為是python可視化數據包的原始數據組。Matplotlib通過50個分散點的比例和不透明度來模擬雨滴落在平面上的情景。
  • matplotlib進階必會!使用OffsetBox盡情的添加你想要的自定義元素!
    在matplotlib中添加自定義圖片有多種方法,本文將基於matplotlib中的Artists容器類講解,如何在我們製作的圖中添加任意自已想要的元素。導入與初始化老規矩,首先我們需要導入相關庫,並創建一張畫布import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import Circlefrom matplotlib.offsetbox
  • Matplotlib二維和三維繪圖細解
    本節提要:
  • matplotlib可視化必知必會富文本繪製方法
    ❝本文示例代碼及文件已上傳至我的Github倉庫https://github.com/CNFeffery/DataScienceStudyNotes❞1 簡介長久以來,在使用matplotlib進行繪圖時,一直都沒有比較方便的辦法像R中的ggtext那樣,向圖像中插入整段的混合風格富文本內容,譬如下面的例子:
  • 基於Python的圖表繪圖系統matplotlib,「動態條形圖」你了解嗎?
    查看並選取符合要求數據先看下數據,依然是英超各球隊的積分數據,製作動態條形圖,對數據量要求會稍微大一些,對於有時間維度的數據來說,時間越長,能體現的變化和信息量就會越多,這裡我們只選取了從2010–2019年英超各球隊的積分數據,這個數據量不算大,但是不影響學習原理和實現步驟。