下图附上代码,还有很详细的代码注释,很容易看懂
import matplotlib.pyplot as plt
import numpy as np
#上面都是最基本的库,首先需要导入
plt.figure(figsize=(12,8), dpi=100,)
#创建画布
plt.rcParams['font.sans-serif'] = ['SimHei']
# 设置字体,matplotlib默认不支持中文,需要引入字体
y_boy = np.array([88, 90, 92, 86, 95])
#男生班级分数,都放在一个列表内
y_girl = np.array([89, 88, 94, 84, 91])
#女生班级分数,也放在一个列表内
x_value = np.arange(5)
#柱状图的数量,取值5就是五个班级的图
bar_wight = 0.4
#柱状图的宽度,变量
x_title = ["高二1班", "高二2班", "高二3班", "高二4班", "高二5班"]
#班级名称字符串存在一个列表内
plt.bar(x_value, y_boy, tick_label=x_title, color="#0eb83a", linestyle="-", width=0.3, label="男生平均成绩")
#bar代表柱状图的方法,分别去x,y值,tick_label是x轴刻度名称
plt.bar(x_value + bar_wight, y_girl, color="#ed5736", width=0.3, label="女生平均成绩")
#这是女生的柱状图,同上
plt.axhline(85, 0, 1, linestyle="--", c="r", label="全体平均成绩")
#这是设置水平线的方法(平均分数线)
plt.legend(loc="lower right")
#图例方法,loc代表图例在哪位置显示,有label方法的默认会显示,不需要特意传值
plt.xlabel("年级")
#x轴说明名称
plt.ylabel("分数")
#y轴说明名称
plt.title("高二各班年级男女平均分数")
#柱状图标题
plt.savefig("1.png")
#保存图片,只填写文件保存路径和后缀就可以了
plt.show()
#show就是把图片展示出来。
2022.4.10日更新,主要对图形添加了辅助内容标签,丰富图表元素,看着更直观
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(10, 101, 10)
x = np.arange(1, 11)
label = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.figure(figsize=(16, 9), dpi=80)
plt.bar(x, y, width=0.5, label="完成量", color="#ed5736")
plt.xticks(np.arange(1, 11, 1), label)
plt.title("测试", fontsize=50)
plt.text(1, 10, "10%", weight="bold", color="b", fontsize=20, ha="center", va="bottom")
plt.text(2, 20, "20%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(3, 30, "30%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(4, 40, "40%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(5, 50, "50%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(6, 60, "60%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(7, 70, "70%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(8, 80, "80%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(9, 90, "90%", weight="bold", color="r", fontsize=20, verticalalignment='bottom', horizontalalignment="center")
plt.text(10, 100, "100%", weight="bold", color="r", fontsize=20, verticalalignment='bottom',
horizontalalignment="center")
plt.annotate("未达标平均线", xy=(1, 80), arrowprops=dict(arrowstyle="<->"), fontsize=20, xytext=(1, 60))
plt.ylim(0, 120)
plt.xlim(0, 11)
plt.axhline(80, linestyle="--", color="r", label="80%水平线", )
plt.xlabel("x轴", fontsize=24)
plt.ylabel("y轴", fontsize=24)
plt.legend(loc="upper left", fontsize=20)
plt.show()
本博客最早更新于2022.4.9日15.20分