首頁 > 軟體

python繪製餅圖的方法詳解

2022-03-17 19:00:30

用法

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, data=None)

引數介紹

引數 
x楔形尺寸
explode類似陣列,預設值: 無,如果不是無,則是一個len(x)陣列,用於指定偏移每個楔塊的半徑
labels標籤列表:預設值:無,為每個楔塊提供標籤的一系列字串
colors顏色,預設值:無,餅圖迴圈使用的一系列顏色,如果沒有,將使用當前活動週期中的顏色
autopct預設值:無,如果不是無,則是一個字串或函數,用於用數位值標記楔塊.標籤將放在楔子內,如果是格式字串,則標籤為fmt%pct,如果是函數,則呼叫
pctdistance預設值為0.6,每個餅圖切片的中心與生成的文字開頭之間的比率
shadow預設值為:False,楔塊的陰影
labeldistance預設值1.1,繪製餅圖示籤徑向距離,如果設定為’無’,則不會繪製標籤,會儲存標籤以供在圖列()中使用
startangle餅圖角度起始角度
radius預設值1,餅圖的半徑,數值越大,餅圖越大
counterclock設定餅圖的方向,預設值為True,表示逆時針方向,False,為順時針
wedgeprops預設值:無,傳遞給楔形物件的引數,設定楔形的屬性
textprops設定文字物件的字典引數
center浮點型別的列表,可選引數,圖示中心位置
frame是否選擇軸框架,預設值為False,如果是True,則繪製帶有表的軸框架
rotatelabels預設值為False,布林型別,如果為True,則將每個標籤旋轉到相應切片的角度
narmalize布林型別,預設值為True,如果為True,則始終通過規範化x來製作完整的餅圖,使總和(x)=1。如果sum(x)<=1,False將生成部分餅圖,併為sum(x)>1引發ValueError。
data可選引數,如果給定,一下引數接受字串s,該字串被解釋為資料[s]

案例

x

import numpy as np
import maplotlib.pyplot as plt
x = [1, 2, 3, 4]
plt.pie(x)
plt.show()

explode

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [1, 2, 3, 4]
plt.subplot(121)
plt.title('正常')
plt.pie(x)
plt.subplot(122)
plt.title('新增explode')
plt.pie(x,explode=[0.1,0.2,0.1,0.2])
plt.show()

labels,labeldistance

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(131)
plt.title('正常')
plt.pie(x)
plt.subplot(132)
plt.title('新增labels')
plt.pie(x,labels=['x1','y1','x2','y2'])
# labeldistance預設為是1.1
plt.subplot(133)
plt.title('新增labels和labeldistance')
plt.pie(x,labels=['x1','y1','x2','y2'],labeldistance=1.2)
plt.show()

colors

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [1, 2, 3, 4]
plt.subplot(121)
plt.title('正常')
plt.pie(x)
# 顏色引數必須保持和x長度一樣
plt.subplot(122)
colors = plt.get_cmap('Blues')(np.linspace(0.2,0.7,len(x)))
print(colors)
plt.title('新增colors')
plt.pie(x,colors=colors)
plt.show()

autopct

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [1, 2, 3, 4]
plt.subplot(131)
plt.title('正常')
plt.pie(x)
plt.subplot(132)
plt.title('新增autopct為1.1f')
plt.pie(x,autopct='%1.1f%%')
plt.subplot(133)
plt.title('新增autopct為10.1f')
plt.pie(x,autopct='%10.1f%%')
plt.show()

pctdistance

import numpy as np
import matplotlib.pyplot as plt

plt.figsize=((10,8))
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [1, 2, 3, 4]
plt.subplot(131)
plt.title('正常')
plt.pie(x)
plt.subplot(132)
plt.title('新增pctdistance預設值0.6')
plt.pie(x,autopct='%1.1f%%',pctdistance=0.6)
plt.subplot(133)
plt.title('新增pctdistance值1.5')
plt.pie(x,autopct='%1.1f%%',pctdistance=0.8)
plt.show()

pctdistance和autopct設定都可以偏移百分比,一個是同方向偏移,一個是距中心點位置

shadow

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(121)
plt.title('正常')
plt.pie(x)
plt.subplot(122)
plt.title('新增shadow')
plt.pie(x,explode=(0,0,0.1,0),shadow=True)

plt.show()

startangle

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(121)
plt.title('正常')
plt.pie(x,autopct='%1.1f%%')
# 起始角度設定
plt.subplot(122)
plt.title('設定startangle=90')
plt.pie(x,autopct='%1.1f%%',startangle=90)

plt.show()

radius

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(121)
plt.title('正常')
plt.pie(x,autopct='%1.1f%%')
plt.subplot(122)
plt.title('設定radius=0.9')
plt.pie(x,autopct='%1.1f%%',radius=0.9)

plt.show()

counterclock

counterclock=False,設定餅圖方向為逆方向

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(121)
plt.title('正常')
plt.pie(x,autopct='%1.1f%%')
plt.subplot(122)
plt.title('設定counterclock=False')
plt.pie(x,autopct='%1.1f%%',counterclock=False)
plt.show()

wedgeprops

設定楔形的屬性

wedgeprops傳入字典型別,width設定,可以轉變為環形圖,edgecolor設定其環形邊緣顏色

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(121)
plt.title('正常')
plt.pie(x,autopct='%1.1f%%')
plt.subplot(122)
plt.title('設定wedgeprops楔形的屬性')
plt.pie(x,autopct='%1.1f%%',wedgeprops=dict(width=0.3, edgecolor='blue'))

plt.show()

textprops,center,frame

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus']=False
x = [15, 30, 45, 10]
plt.subplot(131)
plt.title('正常')
plt.pie(x,autopct='%1.1f%%')
plt.subplot(132)
plt.title('設定textprops,center=1.1,frame')
plt.pie(x,autopct='%1.1f%%',textprops={'size': 'larger'},center=(1,1),frame=True)

plt.subplot(133)
plt.title('設定textprops,center=2.2,frame')
plt.pie(x,autopct='%1.1f%%',textprops={'size': 'x-large'},center=(2,2),frame=True)

plt.show()

rotatelabels,normalize

這裡不多介紹,可根據上述自己檢驗,很少被用到

舉例

1.取餅圖一部分楔形,新增colorbar

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 5))
fig.subplots_adjust(wspace=0)
ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]
angle = -180 * ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
        labels=labels, explode=explode)
xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
colors = [[.1, .3, .5], [.1, .3, .3], [.1, .3, .7], [.1, .3, .9]]
for j in range(len(ratios)):
    height = ratios[j]
    ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
    ypos = bottom + ax2.patches[j].get_height() / 2
    bottom += height
    ax2.text(xpos, ypos, "%d%%" % (ax2.patches[j].get_height() * 100),
             ha='center')
ax2.set_title('Age of approvers')
ax2.legend(('50-65', 'Over 65', '35-49', 'Under 35'))
ax2.axis('off')
ax2.set_xlim(- 2.5 * width, 2.5 * width)

theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
center, r = ax1.patches[0].center, ax1.patches[0].r
bar_height = sum([item.get_height() for item in ax2.patches])
# draw top connecting line
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = r * np.sin(np.pi / 180 * theta2) + center[1]
con = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)
# draw bottom connecting line
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = r * np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData,
                      xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)
plt.show()

2.環形圖

import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
cmap = plt.cm.Set1
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap([1, 2, 5, 6, 9, 10])
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
       wedgeprops=dict(width=size, edgecolor='w'))
ax.pie(vals.flatten(), radius=1-size, colors=inner_colors,
       wedgeprops=dict(width=size, edgecolor='w'))
ax.set(aspect="equal", title='Pie plot with `ax.pie`')
plt.show()

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!   


IT145.com E-mail:sddin#qq.com