matplotlib在一张图同时画折线图和柱状图

实现了在一张图片里用matplotlib的pyplot同时绘制折线图和柱状图。

# -*- coding:utf-8 -*-
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体显示中文

# 构建数据
x = np.arange(1, 15)
y = [0.8, 0.88, 0.825, 0.76, 0.91, 0.95, 0.74, 0.99, 0.80, 0.72, 0.9, 0.81, 0.74, 0.87]
z = [37, 25, 17, 49, 27, 77, 34, 34, 34, 51, 39, 52, 47, 12]
u = [37, 31, 19, 57, 29, 86, 36, 37, 45, 64, 42, 57, 50, 24]


# 绘柱状图
plt.bar(x=x, height=z, label='实际', color='Coral', alpha=0.8)
plt.bar(x=x, height=u, label='总数', color='LemonChiffon', alpha=0.8)
# 在左侧显示图例
plt.legend(loc="upper left")

# 设置标题
plt.title("Detection results")
# 为两条坐标轴设置名称
plt.xlabel("Component number")
plt.ylabel("Number of seam")


# 画折线图
ax2 = plt.twinx()
ax2.set_ylabel("recall")
# 设置坐标轴范围
ax2.set_ylim([0.5, 1.05]);
plt.plot(x, y, "r", marker='.', c='r', ms=5, linewidth='1', label="Recall")
# 显示数字
for a, b in zip(x, y):
    plt.text(a, b, b, ha='center', va='bottom', fontsize=8)
# 在右侧显示图例
plt.legend(loc="upper right")
plt.savefig("recall.jpg")

plt.show()

显示结果:

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 10:05
小米集团 算法工程师 28.0k*15.0
泡沫灬一触即破:楼上那个看来是看人拿高薪,自己又不如意搁这泄愤呢是吧,看你过往评论很难不怀疑你的精神状态
点赞 评论 收藏
分享
2024-12-26 13:00
太原理工大学 Java
会飞的猿:简历没啥大问题啊,感觉是缺少了实习经历。多投投先找个中小厂过渡一下吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务