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

Table of Contents

n

1 官方Demo

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

3 一些改善措施

3.1 重新設置字體大小

3.2 設置顯示顏色,Method 1:

3.3 設置顯示顏色, Method 2:

3.4 設置圖例(legend)

3.5 重新設置圖例(legend)

3.6 將某些類別突出顯示

前言

n

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

n

n

from matplotlib import font_manager as fmnimport matplotlib as mplnimport pandas as pdnimport numpy as npnimport matplotlib.pyplot as pltn% matplotlib inlinenplt.style.use(ggplot)n

n

1. 官方Demo

n

import matplotlib.pyplot as pltnn# Pie chart, where the slices will be ordered and plotted counter-clockwise:nlabels = Frogs, Hogs, Dogs, Logsnsizes = [15, 30, 45, 10]nexplode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. Hogs)nnfig1, ax1 = plt.subplots()nax1.pie(sizes, explode=explode, labels=labels, autopct=%1.1f%%,n shadow=True, startangle=90)nax1.axis(equal) # Equal aspect ratio ensures that pie is drawn as a circle.nnplt.savefig(Demo_official.jpg)nplt.show()n

n

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

n

# 原始數據nshapes = [Cross, Cone, Egg, Teardrop, Chevron, Diamond, Cylinder,n Rectangle, Flash, Cigar, Changing, Formation, Oval, Disk,n Sphere, Fireball, Triangle, Circle, Light]nvalues = [ 287, 383, 842, 866, 1187, 1405, 1495, 1620, 1717,n 2313, 2378, 3070, 4332, 5841, 6482, 7785, 9358, 9818, 20254]nns = pd.Series(values, index=shapes)nsn

n

from matplotlib import font_manager as fmnimport matplotlib as mplnn# Pie chart, where the slices will be ordered and plotted counter-clockwise:nlabels = s.indexnsizes = s.valuesnexplode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slicennfig1, ax1 = plt.subplots()npatches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170)nax1.axis(equal) # Equal aspect ratio ensures that pie is drawn as a circle.nnplt.savefig(Demo_project.jpg)nplt.show()n

n

上圖的一些問題:

n

  1. 顏色比較生硬
  2. n

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

3. 一些改善措施

n

  • 重新設置字體大小
  • n

  • 設置自選顏色
  • n

  • 設置圖例
  • n

  • 將某些類別突出顯示
  • n

3.1 重新設置字體大小

n

from matplotlib import font_manager as fmnimport matplotlib as mplnnlabels = s.indexnsizes = s.valuesnexplode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slicennfig1, ax1 = plt.subplots()nnpatches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170)nax1.axis(equal) # Equal aspect ratio ensures that pie is drawn as a circle.nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnplt.savefig(Demo_project_set_font.jpg)nplt.show()n

n

3.2 設置顯示顏色,Method 1:

n

from matplotlib import font_manager as fmnimport matplotlib as mplnn# Pie chart, where the slices will be ordered and plotted counter-clockwise:nlabels = s.indexnsizes = s.valuesnexplode = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slicennfig1, ax1 = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小nna = np.random.rand(1,19)ncolor_vals = list(a[0])nmy_norm = mpl.colors.Normalize(-1, 1) # 將顏色數據的範圍設置為 [0, 1]nmy_cmap = mpl.cm.get_cmap(rainbow, len(color_vals)) # 可選擇合適的colormap,如:rainbownnpatches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170, colors=my_cmap(my_norm(color_vals)))nnax1.axis(equal) nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnplt.savefig(Demo_project_set_color_1.jpg)nplt.show()n

n

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

n

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

n

3.3 設置顯示顏色, Method 2:

n

from matplotlib import font_manager as fmnfrom matplotlib import cmnnlabels = s.indexnsizes = s.valuesn# 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 slicennfig, ax = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小nncolors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darksnpatches, texts, autotexts = ax.pie(sizes, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170, colors=colors)nnax.axis(equal) nax.set_title(Shapes -------------------, loc=left)nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnplt.savefig(Demo_project_set_color_2.jpg)nplt.show()n

n

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

n

3.4 設置圖例(legend)

n

from matplotlib import font_manager as fmnfrom matplotlib import cmnnlabels = s.indexnsizes = s.valuesn# 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 slicennfig, ax = plt.subplots(figsize=(6,6)) # 設置繪圖區域大小nncolors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darksnpatches, texts, autotexts = ax.pie(sizes, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170, colors=colors)nnax.axis(equal) nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnax.legend(labels, loc=2)nnplt.savefig(Demo_project_set_legend_error.jpg)nplt.show()n

n

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

n

3.5 重新設置圖例(legend)

n

from matplotlib import font_manager as fmnfrom matplotlib import cmnnlabels = s.indexnsizes = s.valuesn# 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 slicennfig, axes = plt.subplots(figsize=(10,5),ncols=2) # 設置繪圖區域大小nax1, ax2 = axes.ravel()nncolors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darksnpatches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct=%1.0f%%,n shadow=False, startangle=170, colors=colors)nnax1.axis(equal) nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnax1.set_title(Shapes, loc=center)nn# ax2 只顯示圖例(legend)nax2.axis(off)nax2.legend(patches, labels, loc=center left)nnplt.tight_layout()nplt.savefig(Demo_project_set_legend_good.jpg)nplt.show()n

n

3.6 將某些類別突出顯示

n

  • 將某些類別突出顯示
  • n

  • 控制label的顯示位置
  • n

  • 控制百分比的顯示位置
  • n

  • 控制突出位置的大小
  • n

from matplotlib import font_manager as fmnfrom matplotlib import cmnnlabels = s.indexnsizes = s.valuesnexplode = (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 slicennfig, axes = plt.subplots(figsize=(8,5),ncols=2) # 設置繪圖區域大小nax1, ax2 = axes.ravel()nncolors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darksnpatches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct=%1.0f%%,explode=explode,n shadow=False, startangle=170, colors=colors, labeldistance=1.2,pctdistance=1.03, radius=0.4)n# labeldistance: 控制labels顯示的位置n# pctdistance: 控制百分比顯示的位置n# radius: 控制切片突出的距離nnax1.axis(equal) nn# 重新設置字體大小nproptease = fm.FontProperties()nproptease.set_size(xx-small)n# font size include: 『xx-small』,x-small』,small』,medium』,『large』,『x-large』,『xx-large』 or number, e.g. 12nplt.setp(autotexts, fontproperties=proptease)nplt.setp(texts, fontproperties=proptease)nnax1.set_title(Shapes, loc=center)nn# ax2 只顯示圖例(legend)nax2.axis(off)nax2.legend(patches, labels, loc=center left)nnplt.tight_layout()n# plt.savefig("pie_shape_ufo.png", bbox_inches=tight)nplt.savefig(Demo_project_final.jpg)nplt.show()n

n

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

n

「Python數據之道」


推薦閱讀:

新手Python,如何系統的學習Python智能演算法?
在 PyCharm 中寫 pip 包應該如何處理引用問題?
Python 的庫函數里有沒有現成的全排列函數?
用python寫程序時,怎麼知道我想實現的功能有沒有現成的函數?
python爬蟲如何深入學習?

TAG:Python | Python库 | 数据可视化 |