# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
from itertools import cycle
from IPython.display import Image
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.font_manager as mfm
import matplotlib.gridspec as gridspec
import matplotlib.ticker as plticker
目标图表形式
加入数据
data = pd.DataFrame(np.array([['5.0', '4.5-5', '4-4.5', '3.5-4', '0-3.5'],
[10, 46, 38, 18, 4]]).T,
columns = ['评论星级','频数']
)
data
直接画出饼图
参数设置,方便后面直接进行使用
font_path = {}
prop = {}
font_path['hei'] = './font/MSYHMONO.ttf'
font_path['english'] = './font/Calibri.ttf'
for font_name in list(font_path):
prop[font_name] = mfm.FontProperties(fname=font_path[font_name])
title_font = prop['hei'].copy()
title_font.set_size(14)
default_colors = {}
default_colors['blue'] = '#6CADDD'
default_colors['yellow'] = '#F3903F'
default_colors['red'] = '#CB615A'
default_colors['orange'] = '#F3903F'
default_colors['gray'] = '#B4B4B4'
default_colors['lightyellow'] = '#FCC900'
default_colors['royalblue'] = '#5488CF'
# 构造颜色的循环迭代器
color_cycle = cycle(['blue', 'orange', 'red', 'lightyellow', 'royalblue'])
# 饼图
fig = plt.figure(figsize=(5.708,2.756))
gs = gridspec.GridSpec(1, 1)
ax = fig.add_subplot(gs[0])
length = len(data)
explode = np.ones(length)*0.03
labels = data['评论星级']
plt.title(u'星级分布', y=1.08, fontproperties=title_font)
colors = list(default_colors.values())
patches = ax.pie(data['频数'], explode=explode, labels=labels, colors=colors, autopct='%d%%')
handles = []
for i, l in enumerate(labels):
handles.append(mpl.patches.Patch(color=colors[i],label=l))
ax.legend(handles, labels, loc="center right", frameon=False)
ax.axis('equal')
gs.tight_layout(fig)
fig
练习
用类的形式做出饼图的模板