1.考察知识点绘制漏斗图
根据表格中的数据,绘制一个由矩形条和线段组成的简易版的漏斗图,要求自定义设置一些辅助元素。
环节 | 数量 |
显示 | 100 |
点击 | 75 |
访问 | 55 |
咨询 | 35 |
订购 | 20 |
代码如下:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
num = 5
height = 0.5
x1 = np.array([100, 75, 55, 35, 20])
x2 = np.array((x1.max() - x1) / 2)
x3 = [i + j for i, j in zip(x1, x2)]
x3 = np.array(x3)
y = -np.sort(-np.arange(num))
labels = ['显示', '点击', '访问', '咨询', '订购']
# 绘制条形图
color_list = [选五个你喜欢的颜色,例如:'#3A5FCD', '#27408B']
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
rects1 = plt.barh(y, x3, height, tick_label=labels, color=color_list, alpha=0.5)
rects2 = plt.barh(y, x2, height, color='w', alpha=1)
# 添加辅助折线
ax.plot(x3, y, 'black', alpha=0.7)
ax.plot(x2, y, 'black', alpha=0.7)
# 添加无指向型注释文本
notes = []
for i in range(0, len(x1)):
notes.append('%.2f%%' % ((x1[i] / x1[0]) * 100))
for rect_one, rect_two, note in zip(rects1, rects2, notes):
text_x = rect_two.get_width() + (rect_one.get_width()
- rect_two.get_width()) / 2 - 3
text_y = rect_one.get_y() + height / 2
ax.text(text_x, text_y, note, fontsize=12)
ax.set_xticks([])
for direction in ['top', 'left', 'bottom', 'right']:
ax.spines[direction].set_color('none')
ax.yaxis.set_ticks_position('none')
plt.show()
2. 考察知识点绘制桑基图
已知小明家当月日常生活的收支明细主要分为收入,副业,生活,购物,深造,聚餐,人情往来,其他几类,且其中每项收入或支出值分别为6000,1000,-1500,-1000,-800,-500,-500,-200。下面结合这些日常生活收支明细的数据绘制一个桑基图,要求自定义设置图表样式。
代码如下:
import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
flows = [6000, 1000, -1500, -1000, -800, -500, -500, -200]
labels = ["收入", "副业", "生活", "购物", "深造", "聚会", "人情往来", "其他"]
orientations = [1, 1, 0, -1, 1, -1, 1, 0]
sankey = Sankey()
sankey.add(flows=flows, labels=labels, orientations=orientations, color="black",
fc="#CD5555", patchlabel="日常生活收支", alpha=0.7, trunklength=500, )
diagrams = sankey.finish()
diagrams[0].texts[4].set_color("g")
diagrams[0].texts[4].set_weight("bold")
diagrams[0].text.set_fontsize(25)
diagrams[0].text.set_fontweight("bold")
plt.title("小明家日常生活收支桑基图")
diagrams[0].texts[0].set_fontsize(15)
diagrams[0].texts[1].set_fontsize(15)
diagrams[0].texts[2].set_fontsize(15)
diagrams[0].texts[3].set_fontsize(15)
diagrams[0].texts[4].set_fontsize(15)
diagrams[0].texts[5].set_fontsize(15)
diagrams[0].texts[6].set_fontsize(15)
diagrams[0].texts[7].set_fontsize(15)
plt.show()