python:matplotlib绘图 —— 绘制双Y轴图表 —— 双Y轴的坐标轴不同颜色-牛翰网

python:matplotlib绘图 —— 绘制双Y轴图表 —— 双Y轴的坐标轴不同颜色

关键代码:

ax1.tick_params(axis=’y’, labelcolor=’b’)

ax2 = ax1.twinx()

ax2.tick_params(axis=’y’, labelcolor=’r’)

实际表现:

效果图:

全部代码:

点击查看代码

import numpy as np
import matplotlib.pyplot as plt



# 设置中文字体显示(如果系统支持)
plt.rcParams['font.sans-serif'] = ['SimHei']  # Windows系统
plt.rcParams['axes.unicode_minus'] = False   # 正确显示负号


# 模拟数据
user_nums = np.array([10, 50, 100, 200, 300, 400, 500])  # 用户数量
latency = 100 + 0.5 * user_nums + 0.002 * user_nums**2    # 网络延迟(非线性增长)
success_rate = 100 - 0.1 * user_nums - 0.0003 * user_nums**2  # 任务成功率(百分比)

# 绘制双Y轴图表
fig, ax1 = plt.subplots(figsize=(10, 6))

# 左侧Y轴:网络延迟
ax1.plot(user_nums, latency, 'b-o', linewidth=2, markersize=8, label='网络延迟')
ax1.set_xlabel('用户数量', fontsize=12)
ax1.set_ylabel('网络延迟 (ms)', color='b', fontsize=12)
ax1.tick_params(axis='y', labelcolor='b')
ax1.grid(linestyle='--', alpha=0.7)

# 右侧Y轴:任务成功率
ax2 = ax1.twinx()
ax2.plot(user_nums, success_rate, 'r--s', linewidth=2, markersize=8, label='任务成功率')
ax2.set_ylabel('任务成功率 (%)', color='r', fontsize=12)
ax2.tick_params(axis='y', labelcolor='r')

# 标题和图例
plt.title('物联网计算卸载:用户数量对网络延迟与任务成功率的影响', fontsize=14)
fig.legend(loc='upper right', bbox_to_anchor=(0.85, 0.85), fontsize=10)

plt.tight_layout()
plt.show()

来源链接:https://www.cnblogs.com/xyz/p/18746143

请登录后发表评论

    没有回复内容