import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False men_means = (85.5, 91, 72, 59, 66, 55) women_means = (94, 82, 89.5, 62, 49, 53) ind = np.arange(len(men_means)) width = 0.2 fig = plt.figure() ax = fig.add_subplot(111) ax.bar(ind - width / 2, men_means, width, label='男生平均成绩') ax.bar(ind + 0.2, women_means, width, label='女生平均成绩') ax.set_title('高二男生女生各科平均成绩') ax.set_xticks(ind) ax.set_xticklabels(['语文', '数学', '英语', '物理', '化学', '生物']) plt.ylim(40, 100) ax.legend() plt.show()美化并转为环形图
时间: 2023-08-08 08:07:55 浏览: 226
以下是美化并转为环形图的代码:
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
men_means = (85.5, 91, 72, 59, 66, 55)
women_means = (94, 82, 89.5, 62, 49, 53)
ind = np.arange(len(men_means))
width = 0.2
fig, ax = plt.subplots(figsize=(8, 8))
ax.bar(ind - width / 2, men_means, width, label='男生平均成绩', color='tab:blue')
ax.bar(ind + 0.2, women_means, width, label='女生平均成绩', color='tab:orange')
ax.set_title('高二男生女生各科平均成绩', fontsize=20)
ax.set_xticks(ind)
ax.set_xticklabels(['语文', '数学', '英语', '物理', '化学', '生物'], fontsize=15)
ax.set_ylim(40, 100)
ax.legend(fontsize=15)
# 环形图部分
theta = np.linspace(0, 2 * np.pi, len(men_means) + 1)
radii = np.repeat(1.5, len(men_means) + 1)
ax1 = plt.subplot(111, projection='polar')
ax1.plot(theta, radii, color='black', linewidth=1)
for i in range(len(men_means)):
ax1.fill_between([theta[i], theta[i+1]], 0, radii[i+1], color='tab:blue', alpha=0.6)
ax1.fill_between([theta[i], theta[i+1]], 0, radii[i], color='tab:orange', alpha=0.6)
posA = ax1.transData.transform((theta[i], radii[i]))
posB = ax1.transData.transform((theta[i], radii[i+1]))
coordsA = ax.transData.inverted().transform(posA)
coordsB = ax.transData.inverted().transform(posB)
con = ConnectionPatch(xyA=coordsA, xyB=coordsB, coordsA="data", coordsB="data", lw=1, color='black', alpha=0.8)
fig.add_artist(con)
plt.tight_layout()
plt.show()
```
这个代码首先绘制了原始的柱状图,然后使用极坐标系绘制了环形图。环形图中,每个扇形的角度与柱状图中每个柱子对应,颜色则代表男女生的成绩。同时,为了使环形图与柱状图对应,我们使用 ConnectionPatch 将两个部分连接起来。最后,使用 tight_layout() 函数调整布局,使得图像更加美观。
阅读全文