|
|
要在 Matplotlib 中创建共享 x 轴的两条折线图,可以使用并设置 sharex=True。以下是实现步骤和代码:
1. 数据准备
将百分比字符串转换为浮点数:
- x = [1, 2, 3, 4, 5]
- y = [1, 3, 4, 6, 8]
- z_str = ['2%', '6%', '8%', '9%', '11%']
- z = [float(i.strip('%')) / 100 for i in z_str] # 转换为小数
复制代码
2. 创建共享 x 轴的子图
- import matplotlib.pyplot as plt
- fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6))
- # 第一个子图:y 折线
- ax1.plot(x, y, marker='o', color='b', label='y')
- ax1.set_ylabel('y 值')
- ax1.legend()
- ax1.grid(True)
- # 第二个子图:z 折线
- ax2.plot(x, z, marker='s', color='r', label='z')
- ax2.set_xlabel('x 值')
- ax2.set_ylabel('z 百分比')
- ax2.legend()
- ax2.grid(True)
- # 调整布局
- plt.tight_layout()
- plt.show()
复制代码
关键点说明
o 使用 subplots(2,1,sharex=True) 创建两个垂直排列的子图并共享 x 轴。
o 两个子图分别绘制 y 和 z 的折线,x 轴会自动对齐。
o 通过 plt.tight_layout() 调整子图间距,避免标签重叠。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|