使用 Python Matplotlib 创建双轴图表,将折线图和柱状图分别显示在图表左右侧,并使用不同的刻度

您可以使用axes.twinx()方法创建一个新的y轴,并将折线图绘制在新的y轴上。然后,使用axes.twiny()方法创建一个新的x轴,并将柱状图绘制在新的x轴上。

以下是修改后的代码示例:

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

username = 'your_username'
toolpath = (r'C:\Users\%s\Desktop' % username)
os.chdir(toolpath)
df = pd.read_csv(r'BatteryMonitor1_modified.csv')
variation_array = df['Variation'].values
variation_str = ','.join(map(str, variation_array))  # 将数据中间用逗号隔开
variation_ray = '[' + variation_str + ']'  # 数据列
print(variation_ray)
capacity_array = df['capacity'].values
capacity_str = ','.join(map(str, capacity_array))  # 将数据中间用逗号隔开
capacity_ray = '[' + capacity_str + ']'  # 数据列
print(capacity_ray)
total_rows = len(df)
print(total_rows)  # 总数量
y1 = np.array(eval(variation_ray))
y2 = np.array(eval(capacity_ray))
x = np.linspace(1, total_rows, len(y1))  # 生成与y长度相同的x坐标

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twiny()

ax1.plot(x, y1, '-', label='Variation', alpha=0.3, color='r')
ax2.bar(x, y2, width=0.4, label='capacity', alpha=0.3, color='b')

ax1.set_xlabel('x')
ax1.set_ylabel('Variation', color='r')
ax2.set_ylabel('capacity', color='b')

ax1.tick_params(axis='y', colors='r')
ax2.tick_params(axis='y', colors='b')
ax3.tick_params(axis='x')

plt.grid(True)
plt.legend()
plt.show()

这样,您就可以在折线图的右侧和柱状图的左侧分别设置刻度。

Python Matplotlib: 双轴图表 - 折线图和柱状图分离显示

原文地址: https://www.cveoy.top/t/topic/ffp3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录