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

使用Matplotlib绘制星巴克收盘价出现折线异常的问题求助

Troubleshooting Your Wonky Starbucks Close Price Plot with Matplotlib

Hey there! Let's figure out why your line plot is coming out abnormal—here are the most common issues and fixes to try:

1. Check if Your Date Index is Sorted

The #1 culprit for weird zig-zag line plots with time series data is usually unsorted dates. Even if you parsed the dates correctly, if your CSV has entries out of chronological order, Matplotlib will plot them in the order they appear in the DataFrame, not time order.

Fix this by sorting your DataFrame by its date index:

import pandas as pd
import matplotlib.pyplot as plt

# Load and filter data
df2 = pd.read_csv('sbux.csv', parse_dates=['date'], index_col='date')
df2 = df2[['close']]

# Sort index to ensure chronological order
df2.sort_index(inplace=True)

# Plot with labels for clarity
plt.plot(df2)
plt.title('Starbucks Daily Close Price')
plt.ylabel('Close Price ($)')
plt.xlabel('Date')
plt.show()

2. Verify the 'close' Column is Numeric

If your close column is stored as strings (maybe due to commas, dollar signs, or invalid values in the CSV), Matplotlib won’t plot it correctly. First check the data type:

print(df2['close'].dtype)

If it returns object (string), convert it to numeric and handle errors:

df2['close'] = pd.to_numeric(df2['close'], errors='coerce')
# Drop rows with invalid values if needed
df2 = df2.dropna(subset=['close'])

3. Handle Missing Values

Missing values (NaN) can cause breaks or odd shifts in your line plot. You can either drop them or fill them with a logical value (like forward-filling the previous day’s price):

# Option 1: Drop rows with NaN
df2 = df2.dropna()

# Option 2: Forward-fill missing values
df2['close'] = df2['close'].ffill()

Quick Debug Tip

Before plotting, always inspect your data to confirm it’s formatted correctly:

print(df2.head())
print(df2.info())

This will show you the date order, data types, and any missing values at a glance.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:55:11