繼續(xù)上一篇:
matplotlib-餅圖
這里主要寫一下關(guān)于autopct
參數(shù)的使用
import matplotlib.pyplot as plt
plt.pie([2,4,4] , autopct='%.1f%%')
plt.show()
autopct,單獨(dú)指定格式化字符串的時(shí)候浑此,都是按照默認(rèn)顯示數(shù)字
這里還可以指定為一個(gè)函數(shù),用函數(shù)可以將我們的標(biāo)簽顯示更豐富
def my_label(pct):
print(pct)
return "{:.1f}%".format(pct)
plt.pie([2,4,4] , autopct=my_label)
plt.show()
繼續(xù)優(yōu)化一下這個(gè)函數(shù)
import numpy as np
def my_label(pct, allvals):
absolute = int(pct/100.*np.sum(allvals))
return "{:.1f}%\n({:d} )".format(pct, absolute)
data=[2,4,4]
plt.pie(data , autopct=lambda x: my_label(x,data))
plt.show()
這里用了匿名函數(shù)香嗓,然后將數(shù)據(jù)集也傳到了函數(shù)里
這個(gè)是參考官方文檔的例子纱扭,但是感覺稍微有點(diǎn)兒問題峡迷,原始數(shù)值是自己算出來的颇象,興許會(huì)有差異吧伍伤,等后面實(shí)際使用時(shí)再看看邢羔。