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

Spyder中Matplotlib绘制股票数据时Y轴刻度异常与时间轴顺序问题求助

Solution to Your Microsoft Stock Chart Issues

Hey there! Let's work through your two main problems with plotting Microsoft's stock data in Spyder/Matplotlib—you're just a few tweaks away from a clean, correct chart.

1. Fixing the Data Order (2014 to 2019)

The root issue here is that your CSV stores dates in reverse order (2019 first, 2014 last). Converting the Date column to datetime doesn't reorder the dataset automatically, so Matplotlib plots the data exactly as it's stored. Here's how to fix it:

  • First, properly convert the Date column to datetime format (you had this commented out, but it's essential for correct X-axis labeling).
  • Then, sort the DataFrame by the Date column in ascending order (oldest to newest) to get the 2014→2019 flow you want.

2. Fixing Y-Axis Tick Display

Your Y-axis ticks weren't showing because of two critical missteps:

  • You set plt.ylim(0, 1511)—that upper limit is way too high (Microsoft's stock price in 2019 wasn't over 1500!), so the ticks [0,140] got compressed to the bottom of the chart and became invisible.
  • You also had incomplete code for converting the Close column to a numeric type (it was commented out, so Close might still be a string, which can cause plotting glitches or incorrect scaling).

Full Corrected Code

import pandas as pd
import matplotlib.pyplot as plt

file = 'Microsoft.csv'
df = pd.read_csv(file)

# Step 1: Clean and convert the Close price column to numeric values
df['Close'] = df['Close'].str.replace('$', '', regex=False).astype(float)

# Step 2: Convert Date to datetime and sort data to 2014→2019 order
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
df.sort_values('Date', inplace=True)

# Step 3: Plot with correct Y-axis settings
plt.plot(df.Date, df.Close)
# Set custom Y-axis ticks (adjust this list to your preferred intervals)
plt.yticks([0, 20, 40, 60, 80, 100, 120, 140])
# Set Y-axis limits to match your ticks (add a small buffer for clarity)
plt.ylim(bottom=0, top=145)

plt.suptitle('Stock Price')
plt.title('Microsoft', fontdict={'fontsize':15,'fontweight':'bold'})
plt.xlabel('Year')
plt.ylabel('Price in USD')
# Rotate X-axis dates to avoid overlapping (optional but helpful)
plt.xticks(rotation=45)

plt.tight_layout()  # Fixes label clipping issues
plt.show()

Key Explanations

  • Cleaning Close: Removing the dollar sign and converting to float is mandatory—Matplotlib can't plot string values correctly, which might have been causing hidden scaling issues.
  • Sorting by Date: df.sort_values('Date') rearranges your rows so the oldest date is first, ensuring the plot flows left-to-right from 2014 to 2019.
  • Y-axis Adjustments: Matching ylim to your yticks ensures the ticks are visible and evenly spaced. tight_layout() fixes any clipping of X/Y labels, and rotating X-axis dates makes them easier to read.

If you still see tick visibility issues in Spyder, double-check that your plot window is large enough (small windows can sometimes hide ticks). Switching to non-inline mode might help with visibility, but the core fixes above should resolve your main problems.

内容的提问来源于stack exchange,提问作者Anchor Man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:33:09