python - Matplotlib 绘制多条线不起作用

标签 python matplotlib

当我尝试使用以下代码显示 LSTM 和 RNN 模型预测结果时:

plt.figure(figsize=(5, 3))

plt.plot(y_test, c="orange", linewidth=3, label="Original values")
plt.plot(lstm_pred, c="red", linewidth=3, label="LSTM predictions")
plt.plot(rnn_pred, alpha=0.5, c="green", linewidth=3, label="RNN predictions")
plt.legend()
plt.xticks(rotation=45)
plt.title("Predictions vs actual data", fontsize=20)
plt.show()

如果我将它们一一绘制,线条将正确显示。

enter image description here

thon

enter image description here

但是在一个图中显示所有线条,线条显示不正确。有人知道如何修复它吗?谢谢。

enter image description here

最佳答案

正如评论中提到的you need to create a second Y axis 。 然后你需要合并legend together

fig, ax1 = plt.subplots()

line1 = ax1.plot(y_test, c="orange", linewidth=3, label="Original values")
line2 = ax1.plot(rnn_pred, alpha=0.5, c="green", linewidth=3, label="RNN predictions")
plt.xticks(rotation=45)
ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
line3 = ax2.plot(lstm_pred, c="red", linewidth=3, label="LSTM predictions")

# added these three lines
lines = line1+line2+line3
labels = [l.get_label() for l in lines]
ax.legend(lns, labels)

plt.title("Predictions vs actual data", fontsize=20)
plt.show()

关于python - Matplotlib 绘制多条线不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59030621/

相关文章:

python - 使用组标签 ?P<> 正则表达式到字典

python - 将文件中的元素与嵌套字典python匹配

python - 使用 python 和 matplotlib 绘制 Excel 工作表?

python-3.x - 将 "matplotlib"添加到 cx_Freeze 中的包不起作用

python - click lib 是否提供打印内置帮助消息的方法?

Python:从函数分配对象的变量(OpenERP)

python - 检查父线程是否正在运行

python - 使用来自CPU的实时数据实现matplotlib动画的更好方法?

python - 在 ipython 和 Spark 中通过 mpld3 在散点图中使用工具提示的问题

python - 使用子图和带有 matplotlib 的颜色条将 x 轴与 sharex 对齐