实验四子图的绘制及坐标轴共享

1. 考察知识点绘制固定区域的多子图及坐标轴共享

按照下列要求绘制图表。

  1. 画布被规划为2×3的规划区域;
  2. 在编号为3的区域中绘制包含一条正弦曲线的子图;
  3. 在编号为5的区域中绘制包含一条余弦曲线的子图;
  4. 共享两个子图的x轴;
  5. 要求自定义添加一些常见的辅助元素,如刻度标签、标题等。

代码如下:

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
fig, axs = plt.subplots(2, 3, constrained_layout=True)
x = np.linspace(0, 2 * np.pi, 256, endpoint=True)
y1 = np.sin(x)
y2 = np.cos(x)
ax1 = plt.subplot(233)
ax1.plot(x, y1)
ax1.set_title('sin(x)')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax2 = plt.subplot(235, sharex=ax1)
ax2.plot(x, y2)
ax2.set_title('cos(x)')
ax2.set_xlabel('x')
ax2.set_ylabel('y')

plt.show()

2. 考察知识点绘制自定义区域的子图

编写程序。基于下表数据,设计子图的非等分布局,绘制展示商家A与商家B的柱形图,并分别绘制商家A与商家B的饼图。要求添加常用的辅助元素,如标签、标题等。所绘图形大致如下图所示。

商家

衬衫

毛衣

领带

裤子

风衣

高跟鞋

袜子

商家A

120

56

28

98

129

28

107

商家B

60

140

153

145

160

70

54

 代码如下:

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

data_a = np.array([120, 56, 28, 98, 129, 28, 107])
data_b = np.array([60, 140, 153, 145, 160, 70, 54])
labels = np.array(['衬衫', '毛衣', '领带', '裤子', '风衣', '高跟鞋', '袜子'])
tick_label = ['衬衫', '毛衣', '领带', '裤子', '风衣', '高跟鞋', '袜子']
ax_one = plt.subplot2grid((3, 2), (0, 0), rowspan=2, colspan=2)
x = np.arange(7)
y1 = np.array([120, 56, 28, 98, 129, 28, 107])
y2 = np.array([60, 140, 153, 145, 160, 70, 54])
xx = range(len(tick_label))
bar_rect = plt.bar(x, y1, tick_label=['衬衫', '毛衣', '领带', '裤子', '风衣', '高跟鞋', '袜子'],
                   align='edge', width=0.3)
plt.bar(x + 0.4, y2, align='edge', width=0.3)
kinds = ['商家A', '商家B']
for a, b in zip(x + 0.2, y1):
    plt.text(a, b, '%.0f' % b, ha='center', va='bottom', fontsize=12);
for a, b in zip(x + 0.5, y2):
    plt.text(a, b, '%.0f' % b, ha='center', va='bottom', fontsize=12);
plt.xticks([index + 0.35 for index in xx], tick_label)
plt.legend(kinds)
plt.yticks([0, 50, 100, 150], ['0', '50', '100', '150'])
plt.ylabel('销售额')
ax_two = plt.subplot2grid((3, 2), (2, 0))
ax_two.pie(data_a, radius=1.5, labels=labels, autopct='%3.1f %%',
           colors=['#2F4F4F', '#FF0000', '#228B22', '#FFD700', '#B0C4DE', '#6495ED', '#9370DB'])
ax_two.set_title('商家A销售情况饼图',pad=15)
ax_two.set_aspect('equal')
ax_thr = plt.subplot2grid((3, 2), (2, 1))
ax_thr.pie(data_b, radius=1.5, labels=labels, autopct='%3.1f %%',
           colors=['#2F4F4F', '#FF0000', '#228B22', '#FFD700', '#B0C4DE', '#6495ED', '#9370DB'])
ax_thr.set_title('商家B销售情况饼图',pad=15)
ax_thr.set_aspect('equal')
plt.tight_layout()
plt.show()

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值