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轴日期显示混乱、折线顺序逻辑错误)
样本数据:
| Date | Stock Name | Open | Close | High | Volume | sentiment_score | |
|---|---|---|---|---|---|---|---|
| 12 | 2022-02-01 | TSLA | 311.736664 | 310.416656 | 314.566681 | 73138200 | 17.0517 |
| 33 | 2022-03-01 | TSLA | 289.893341 | 288.123322 | 296.626678 | 74766900 | 16.8564 |
| 50 | 2022-04-01 | TSLA | 360.383331 | 361.529999 | 364.916656 | 54263100 | 11.4832 |
| 67 | 2022-06-01 | TSLA | 251.720001 | 246.789993 | 257.326660 | 77247900 | 12.9977 |
| 86 | 2022-07-01 | TSLA | 227.000000 | 227.263336 | 230.229996 | 74460300 | 11.1603 |
问题原因
- 日期格式未解析:样本中
Date列是字符串类型,matplotlib无法识别为时间序列,导致x轴排序混乱 - 数据索引不连续:原始数据索引为非连续值(12、33等),可能导致绘图时数据顺序错误
- 双轴图例绑定不规范:原代码的图例拼接方式容易引发显示异常
修复后的代码
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
相关产品推荐
相关产品推荐

