Matplotlib数据可视化(6):饼图与箱线图
奥辰 人气:1
In [1]:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体支持
1 饼图-pie()¶
1.1 pie()方法参数说明¶
pie()是matplotlib中画饼图的方法,其主要参数如下:
1.2 基础作图¶
In [2]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(111)
ax1.pie(sizes, labels=labels)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
1.3 字符标签与数值标签¶
In [3]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.pie(sizes,
labels=labels, # 字符标签
labeldistance=1.1, # 字符标签到中心点的距离
autopct='%1.1f%%', # 显示数值标签
pctdistance=0.5 #数值标签到中心点的距离
)
ax2 = fig.add_subplot(122)
ax2.pie(sizes,
labels=labels, # 字符标签
labeldistance=0.4, # 字符标签到中心点的距离
autopct='%1.2f%%', # 显示数值标签
pctdistance=1.2, #数值标签到中心点的距离
rotatelabels=True # 旋转标签
)
plt.show()
1.4 扇形分隔距离¶
In [4]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
fig = plt.figure(figsize=(8, 4))
explode1 = (0.1, 0.1, 0.1, 0.1)
ax1 = fig.add_subplot(121)
ax1.pie(sizes, explode=explode1, # 分隔扇形
labels=labels, autopct='%1.1f%%')
explode2 = (0.1, 0, 0, 0)
ax2 = fig.add_subplot(122)
ax2.pie(sizes, explode=explode2, # 分隔扇形
labels=labels, autopct='%1.1f%%')
plt.show()
1.5 阴影与边框¶
In [5]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, # 显示阴影
wedgeprops = {'linewidth': 3} # 设置边框宽度
)
plt.show()
1.6 旋转图形¶
In [6]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True,
startangle=90 # 旋转
)
plt.show()
1.7 单独设置某一扇形¶
pie()方法返回一个tuple,第一个元素为每个扇形对象组成的list,第二个元素为每个扇形的标签Text对象,第三个元素为每个扇形的数值标签对象,通过这三个对象,可以实现对单一扇形的设置。
In [7]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots()
patches, texts, autotexts = ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%')
print('第1个返回值:',patches)
print('第2个返回值:',texts)
print('第3个返回值:',autotexts)
texts[0].set_color('red') # 设置第一个扇形的字符标签字体颜色
texts[0].set_fontsize(30) # 设置第一个扇形的字符标签字体大小
autotexts[0].set_color('white') # 设置第一个扇形的数值标签字体颜色
plt.show()
第1个返回值: [<matplotlib.patches.Wedge object at 0x7f74ce83bf10>, <matplotlib.patches.Wedge object at 0x7f74ce847590>, <matplotlib.patches.Wedge object at 0x7f74ce847d50>, <matplotlib.patches.Wedge object at 0x7f74ce852590>] 第2个返回值: [Text(0.9068994725035225, 0.7858329000320824, 'Python组'), Text(-1.0005952104475537, 0.4569564802357176, 'Java组'), Text(0.15654637770487598, -1.0888035780743386, 'C组'), Text(1.055442297353649, -0.30990572269135586, 'Go组')] 第3个返回值: [Text(0.5290246922937214, 0.4584025250187147, '22.7%'), Text(-0.5457792056986657, 0.2492489892194823, '40.9%'), Text(0.0853889332935687, -0.593892860767821, '27.3%'), Text(0.5756957985565357, -0.1690394851043759, '9.1%')]
In [8]:
labels = 'Python组', 'Java组', 'C组', 'Go组'
sizes = [25, 45, 30, 10]
explode = (0.1, 0, 0, 0)
fig1, ax1 = plt.subplots(figsize=(5, 5))
patches, texts, autotexts = ax1.pie(sizes, explode=explode, autopct='%1.1f%%')
ax1.legend(patches, labels, loc="upper right",bbox_to_anchor=(0.75, 0, 0.5, 0.4))
plt.show()
1.8 嵌套饼图¶
In [9]:
sizes = {
'Python组':{'男':10, '女': 15},
'Java组':{'男':15, '女': 30},
'C组':{'男':5, '女': 25},
'Go组':{'男':4, '女': 6}
}
def func(sizes):
"""提取数据和标签"""
data1 = []
data2 = []
data2_label = []
for key in sizes.keys():
data1.append(sizes.get(key).get('男') + sizes.get(key).get('女'))
data2.append(sizes.get(key).get('男'))
data2_label.append(key+'-'+'男')
data2.append(sizes.get(key).get('女'))
data2_label.append(key+'-'+'女')
return data1, data2, sizes.keys(), data2_label
data1, data2, data1_label, data2_label = func(sizes)
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(4)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10, 13, 14]))
fig = plt.figure(figsize=(10, 4))
ax1 = fig.add_subplot(121)
ax1.pie(data1, labels=data1_label, radius=1.5, colors=outer_colors, autopct='%1.1f%%', labeldistance=1, pctdistance=0.8)
ax1.pie(data2, labels=data2_label, radius=1, colors=inner_colors, autopct='%1.1f%%', labeldistance=0.4, pctdistance=0.9)
ax2 = fig.add_subplot(122)
ax2.pie(data1, labels=data1_label, radius=1.5, colors=outer_colors, autopct='%1.1f%%', labeldistance=1, pctdistance=0.8,wedgeprops=dict(width=0.8, edgecolor='w'))
ax2.pie(data2, labels=data2_label, radius=1, colors=inner_colors, autopct='%1.1f%%', labeldistance=0.4, pctdistance=0.9,wedgeprops=dict(width=0.6, edgecolor='w'))
plt.show()
2 箱线图¶
2.1 参数说明¶
matplotlib绘制箱线图通过boxplot()方法实现,主要参数如下:
boxplot()方法返回值是一个dict,键值包括'whiskers'、'caps'、'boxes'、'fliers'、'means',分别表示须线、顶端末端线段、箱体、异常数据、均值等绘图对象分别组成的列表,通过这些对象可以横放把您的实现箱线图各个部分的自定义设置。
2.2 基础作图¶
In [ ]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 8))
ax1 = fig.add_subplot(221)
ax1.set_title('图1 常规作图')
ax1.boxplot(data)
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(222)
ax2.set_title('图2 多图绘制')
ax2.boxplot(muti_data)
ax3 = fig.add_subplot(223)
ax3.set_title('图3 水平箱线图')
ax3.boxplot(data, vert=False)
ax4 = fig.add_subplot(224)
ax4.set_title('图4 中间凹陷')
ax4.boxplot(data, notch=True)
plt.show()
2.3 修改标签¶
In [ ]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('图1')
ax2.boxplot(muti_data, labels=['第1组', '第2组', '第3组'])
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(122)
ax2.set_title('图2')
ax2.boxplot(muti_data, vert=False, labels=['第1组', '第2组', '第3组'])
plt.show()
2.4 显示均值¶
In [ ]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('图1')
ax2.boxplot(muti_data, labels=['第1组', '第2组', '第3组'], showmeans=True) # 显示均值,默认以点的方式显示
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(122)
ax2.set_title('图2')
ax2.boxplot(muti_data, labels=['第1组', '第2组', '第3组'], showmeans=True, meanline=True) # 显示均值,并以横线方式显示
plt.show()
2.5 箱体设置¶
In [ ]:
data=np.random.normal(0,4,100)
fig = plt.figure(figsize=(8, 4))
muti_data=[np.random.normal(0,std,100) for std in range(1,4)]
ax2 = fig.add_subplot(121)
ax2.set_title('图1')
box_dict = ax2.boxplot(muti_data, labels=['第1组', '第2组', '第3组'], patch_artist=True) # 注意,patch_artist一定要设置为True,下面的设置才会生效
box_dict.get('boxes')[0].set_color('red') # 箱体边框颜色
box_dict.get('boxes')[1].set_color('blue')
box_dict.get('boxes')[2].set_color('green')
plt.show()
加载全部内容