You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Lab折线图问题:股价与情感分数折线无法正常识别

解决股票价格与情感分数双折线图可视化异常问题

问题背景

需求:绘制两条独立折线分别展示股票价格(Close)与情感分数(sentiment_score)。

原代码:

import matplotlib.pyplot as plt

# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))

# Plot stock prices
ax.plot(tsla['Date'], tsla['Close'], color='blue', label='Stock Prices')

# Create a second y-axis
ax2 = ax.twinx()

# Plot sentiment scores
ax2.plot(tsla['Date'], tsla['sentiment_score'], color='red', label='Sentiment Scores')

# Set labels and titles
ax.set_xlabel('Date')
ax.set_ylabel('Stock Prices', color='blue')
ax2.set_ylabel('Sentiment Scores', color='red')
plt.title('Stock Prices and Sentiment Scores Over Time')

# Add legends
lines = ax.get_lines() + ax2.get_lines()
labels = [line.get_label() for line in lines]
plt.legend(lines, labels, loc='upper left')

# Rotate x-axis tick labels for better readability
plt.xticks(rotation=45)

# Show the plot
plt.show()

异常表现:生成的折线图无法正常识别(x轴日期显示混乱、折线顺序逻辑错误)

样本数据:

DateStock NameOpenCloseHighVolumesentiment_score
122022-02-01TSLA311.736664310.416656314.5666817313820017.0517
332022-03-01TSLA289.893341288.123322296.6266787476690016.8564
502022-04-01TSLA360.383331361.529999364.9166565426310011.4832
672022-06-01TSLA251.720001246.789993257.3266607724790012.9977
862022-07-01TSLA227.000000227.263336230.2299967446030011.1603

问题原因

  1. 日期格式未解析:样本中Date列是字符串类型,matplotlib无法识别为时间序列,导致x轴排序混乱
  2. 数据索引不连续:原始数据索引为非连续值(12、33等),可能导致绘图时数据顺序错误
  3. 双轴图例绑定不规范:原代码的图例拼接方式容易引发显示异常

修复后的代码

import matplotlib.pyplot as plt
import pandas as pd

# 转换日期格式并按时间排序
tsla['Date'] = pd.to_datetime(tsla['Date'])
tsla = tsla.sort_values('Date').reset_index(drop=True)

# 创建画布与主坐标轴
fig, ax = plt.subplots(figsize=(10, 6))

# 绘制股票价格折线
line_price, = ax.plot(tsla['Date'], tsla['Close'], color='blue', label='Stock Prices')
ax.set_xlabel('Date')
ax.set_ylabel('Stock Prices', color='blue')
ax.tick_params(axis='y', labelcolor='blue')

# 创建双Y轴并绘制情感分数折线
ax2 = ax.twinx()
line_sentiment, = ax2.plot(tsla['Date'], tsla['sentiment_score'], color='red', label='Sentiment Scores')
ax2.set_ylabel('Sentiment Scores', color='red')
ax2.tick_params(axis='y', labelcolor='red')

# 设置标题与图例
plt.title('Stock Prices and Sentiment Scores Over Time')
ax.legend(handles=[line_price, line_sentiment], loc='upper left')

# 优化x轴标签显示
plt.xticks(rotation=45, ha='right')
plt.tight_layout()  # 自动调整布局,避免标签被截断

plt.show()

修复说明

  • 将Date列转换为datetime类型,让matplotlib正确解析时间顺序
  • 按日期排序数据并重置索引,保证折线严格按时间先后绘制
  • 直接通过线条对象绑定图例,避免双轴图例冲突
  • 添加plt.tight_layout()和标签右对齐,解决x轴标签被截断的问题

内容的提问来源于stack exchange,提问作者Ayaz Aliyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 18:50:31