簡述
幫助朋友來做一個畫餅圖的任務,給了一系列數據,然後畫出餅圖。
理論上來講應該是很快速的,而且這個任務也很簡單。
但是存在一些小的坑,總是需要我查找以前的做的東西,慢慢填上,耗費了一點時間。
這點時間上的耗費,讓我覺得甚至不如直接用excel畫個圖。
爲了解決這個時間上的消耗問題,這裏我將這些坑都整理了一下,讓以後調用的時候更加方便。
代碼
import matplotlib.pyplot as plt
def pie(data, index_map=None, Chinese=False, autopct="%.2f%%", legend=False, legend_loc=None, save_name=None, dpi=None):
data = data.value_counts()
# 標籤是否映射
if index_map:
data.index = data.index.map(index_map)
# 是否存在中文
if Chinese:
plt.rcParams['font.sans-serif']=['SimHei'] # 用來正常顯示中文標籤
plt.rcParams['axes.unicode_minus']=False # 用來正常顯示負號
# 是否顯示餅內文字
if autopct:
data.plot.pie(autopct=autopct)
else:
data.plot.pie()
# 是否顯示懸浮框
if legend:
# 是否設定位置
if legend_loc:
plt.legend(loc=legend_loc)
else:
plt.legend()
# 是否保存
if save_name:
if not dpi:
dpi=100
plt.savefig(save_name, dpi=dpi)
調用實例
df.iloc[:, 1]
表示選取dataframe的第一列的數據,作爲輸入。
這個數據就是一系列的標籤,比如label1,label2等等之類的。
而我使用的這個數據的這一列內容是,數字1,2,3等等。
所以,我才需要添加一個新的index_map來映射到日常中用到的具體標籤,而不是某個某個抽象的數字。
當然,如果之前的這一列已經就是我們想要的標籤的話,就直接使用就好了。
參數描述
- index_map:一個index的映射函數。
- Chinese:是否用到了中文
- legend:是否有懸浮框
- legend_loc:懸浮框的位置
- save_name:圖片保存的名字 or 路徑
- dpi:圖片精度
d = ['90分及以上','80-89.5分','79.5分及以下']
pie(df.iloc[:, 1], index_map=lambda x: d[int(x-1)], Chinese=True, legend=True, legend_loc="upper left", save_name="test.png", dpi=200)
legend_loc還有其他的屬性:'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center', 'best'