1. 程式人生 > 實用技巧 >python畫餅圖(兩種偶)

python畫餅圖(兩種偶)

Pie(芒果派還是草莓派)

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pylab import mpl
import seaborn as sns
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure(facecolor='snow')
sns.set_style("darkgrid", {"font.sans-serif": ['simhei
', 'Droid Sans Fallback']}) font_size = 11 font_family = "SimHei" font_weight = "bold" plt.rc("font", size=font_size, family=font_family, weight=font_weight) def myPie(): data = [1249,1462,1728,1771,978] labels = ['2015','2016','2017','2018','2019'] explode = [0,0,0.3,0,0] colors = ['red','hotpink
','purple','orange','yellow'] plt.axes(aspect="equal") #保證正圓 plt.xlim(0,8) plt.ylim(0,8) plt.gca().spines['right'].set_color('white') plt.gca().spines['top'].set_color('white') plt.gca().spines['left'].set_color('white') plt.gca().spines['bottom'].set_color('white') #
繪製餅圖 plt.pie(x=data, # 繪製資料 labels=labels, # 新增程式語言標籤 explode=explode, # 突出顯示Python colors=colors, # 設定自定義填充色 autopct='%.2f%%', # 設定百分比的格式,保留2位小數 pctdistance=0.8, # 設定百分比標籤和圓心的距離 labeldistance=1.37, # 設定標籤和圓心的距離 startangle=160, # 設定餅圖的初始角度 center=(4, 4), # 設定餅圖的圓心(相當於X軸和Y軸的範圍) radius=2.6, # 設定餅圖的半徑(相當於X軸和Y軸的範圍) counterclock=False, # 是否為逆時針方向,False表示順時針方向 wedgeprops={'linewidth': 1, 'edgecolor': 'pink'}, # 設定餅圖內外邊界的屬性值 # textprops={'fontsize': 19, 'color': 'black', 'fontproperties': my_font}, # 設定文字標籤的屬性值 textprops={'fontsize': 10, 'color': 'black'}, # 設定文字標籤的屬性值 frame=1) # 是否顯示餅圖的圓圈,1為顯示 # 不顯示X軸、Y軸的刻度值 plt.xticks(()) plt.yticks(()) # 新增圖形標題 # plt.title('專利分佈', fontproperties=my_font) # plt.title('distribution of Food') # 顯示圖形 plt.show() fig.savefig('res/pic/4.png') def axPie(): fig, ax = plt.subplots(figsize=(8, 4), subplot_kw=dict(aspect="equal")) recipe = ['2015y 1249', '2016y 1462', '2017y 1728', '2018y 1771', '2019y 978'] data = [1249,1462,1728,1771,978] """ 引數wedgeprops以字典形式傳遞,設定餅圖邊界的相關屬性,例如圓環寬度0.5 餅狀圖預設從x軸正向沿逆時針繪圖,引數startangle可指定新的角(例如負40度)度起畫 """ wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40) # 建立字典bbox_props,設定文字框的邊框樣式(boxstyle:方框,pad設定方框尺寸)、前景色(fc)為白色(w)、邊框顏色(ec)為黑色(k)、線粗(lw)為0.72 bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72) """ 引數集kw以字典形式傳遞,包含一系列用於繪圖標註的指定引數 xycoords用於指定點xy的座標環境,xycoords='data'表示沿用被註釋的物件所採用的座標系(預設設定) textcoords用於指定點xytext的座標環境,textcoords='data'表示沿用被註釋的物件所採用的座標系(預設設定) 引數arrowprops以字典形式傳遞,用於控制箭頭的諸多屬性,如箭頭型別(arrowstyle)、箭頭連線時的彎曲程度(connectionstyle) """ kw = dict(xycoords='data', textcoords='data', arrowprops=dict(arrowstyle="-"), bbox=bbox_props, zorder=0, va="center") for i, p in enumerate(wedges): # 遍歷每一個扇形 ang = (p.theta2 - p.theta1) / 2. + p.theta1 # 鎖定扇形夾角的中間位置,對應的度數為ang # np.deg2rad(x)將度數x轉為弧度(x*pi)/180 y = np.sin(np.deg2rad(ang)) # np.sin()求正弦 x = np.cos(np.deg2rad(ang)) # np.cos()求餘弦 """ np.sign()符號函式:大於0返回1.0,小於0返回-1.0,等於0返回0.0 引數horizontalalignment用於設定垂直對齊方式,可選引數:left、right、center 當餘弦值x大於0(即標籤在餅圖右側時,按框左側對齊)時,horizontalalignment="left" 當餘弦值x小於0(即標籤在餅圖左側時,按框右側對齊)時,horizontalalignment="right" """ horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))] connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 引數connectionstyle用於控制箭頭連線時的彎曲程度 kw["arrowprops"].update({"connectionstyle": connectionstyle}) # 將connectionstyle更新至引數集kw的引數arrowprops中 """ 用一個箭頭/橫線指向要註釋的地方,再寫上一段話的行為,叫做annotate ax.annotate()用於對已繪製的圖形做標註 recipe[i]是第i個註釋文字 size設定字型大小 xy=(x1, y1)表示在給定的xycoords中,被註釋物件的座標點 xytext=(x2, y2)表示在給定的textcoords中,註釋文字的座標點 """ ax.annotate(recipe[i], size=15, xy=(x, y), xytext=(1.35 * np.sign(x), 1.4 * y), horizontalalignment=horizontalalignment, **kw) ax.set_title("") plt.show() fig.savefig('res/pic/3.png') if __name__ == "__main__": # drawLineStyle() # axPie() myPie()

myPie:

axPie: