我的科研论文中需要绘制一个精美的折线图,我的折线图中有三条曲线,分别表示期望角速度指令信号,和实际的角速度信号,还有实际的航向角信号,现在我已经拥有了数据,使用Python中matplotlib.plt.plot来直接绘制不够精美,我希望绘制一个精美的折线图,要求是:
下面提供实例,代码作为模板
from cProfile import label
from tkinter.ttk import Style
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.spatial.distance import cdist
from matplotlib.ticker import AutoMinorLocator
# 假定你已经有了数据,这里我用随机数代替
# time为时间轴数据,yaw_rate_cmd为期望角速度指令,yaw_rate_real为实际角速度信号,heading_angle为实际航向角信号
time = np.linspace(0, 10, 100)
yaw_rate_cmd = np.sin(time) # 示例数据
yaw_rate_real = np.sin(time - 0.5) * 0.8 # 示例数据
heading_angle = np.piecewise(time, [time < 3, (time >= 3) & (time < 6), time >= 6], [45, 90, 135]) # 示例数据
# 创建图像和轴对象
fig, ax1 = plt.subplots()
# 设置绘图风格
plt.style.use('seaborn-whitegrid')
# 绘制实际角速度信号(置于底层,用小点表示)
ax1.plot(time, yaw_rate_real, 'k:', label='Actual Yaw Rate', zorder=1)
# 创建共享x轴的第二个y轴
ax2 = ax1.twinx()
# 绘制期望角速度信号(置于中层,用实线表示)
ax1.plot(time, yaw_rate_cmd, 'b-', label='Desired Yaw Rate', zorder=2)
# 绘制实际航向角信号(置于顶层,用实线表示)
ax2.plot(time, heading_angle, 'r-', label='Heading Angle', zorder=3)
# 指定的时间点
time_points = [3,6.25]
# # 对于每一个指定的时间点,画一条虚线
for time_point in time_points:
plt.axvline(x=time_point, color='g', linestyle='--', label='Significant Change' if time_point == time_points[0] else "")
# 因为所有虚线都具有相同的意义,所以我们只需要在图例中表示一次
# 检查time_point是否为第一个指定时间点,如果是,则添加图例标签
# 设置轴标题
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Yaw Rate (degrees/s)', color='b')
ax2.set_ylabel('Heading Angle (degrees)', color='r')
# 设置y轴颜色与曲线颜色一致
ax1.tick_params(axis='y', colors='blue')
ax2.tick_params(axis='y', colors='red')
# 增加图例
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper right')
# 增加次要刻度线以提高可读性
ax1.xaxis.set_minor_locator(AutoMinorLocator())
ax1.yaxis.set_minor_locator(AutoMinorLocator())
ax2.yaxis.set_minor_locator(AutoMinorLocator())
# 显示图像
plt.show()
