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

使用Pandas.DataFrame.plot()绘制Close列时的轴值问题

Hey there! Let's figure out why you're running into axis value issues when plotting the Close column with pandas. First, let's recap your DataFrame's head (formatted for clarity):

DateOpenHighLowCloseVolumeMarket Cap
Apr 09, 20187044.327178.116661.996770.734894060000119516000000
Apr 08, 20186919.987111.566919.987023.523652500000117392000000
Apr 07, 20186630.517050.546630.516911.093976610000112467000000
Apr 06, 20186815.966857.496575.006636.323766810000115601000000
Apr 05, 20186848.656933.826644.806811.475639320000116142000000

Looking at this, the most likely culprit is that your Date column is stored as a string (text) instead of a proper datetime type, and it hasn't been set as the DataFrame's index. Pandas can't properly interpret string values as a time axis, which leads to weird axis labeling, incorrect ordering, or missing values in your plot.

Step 1: Convert and set the Date column as a DatetimeIndex

First, we need to turn that string Date column into datetime objects and make it the index of your DataFrame. We'll also sort the index so the dates run from oldest to newest (your current data is reverse-ordered):

import pandas as pd

# Convert Date column to datetime type
df['Date'] = pd.to_datetime(df['Date'])
# Set Date as the index
df.set_index('Date', inplace=True)
# Sort the index to get chronological order
df = df.sort_index()

Step 2: Plot the Close column correctly

Now that we have a proper DatetimeIndex, plotting should work as expected. You can also add labels and a title to make the plot more readable:

plot = df['Close'].plot()
# Add axis labels and title
plot.set_xlabel('Date')
plot.set_ylabel('Close Price')
plot.set_title('Daily Close Price Trend')

Step 3: Fix common axis display issues

If you still run into problems like overlapping date labels or unreadable formatting, tweak the matplotlib settings to clean it up:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

plot = df['Close'].plot()
# Rotate x-axis labels to prevent overlap
plt.xticks(rotation=45)
# Format dates to match your original data style (e.g., "Apr 09, 2018")
date_formatter = DateFormatter("%b %d, %Y")
plot.xaxis.set_major_formatter(date_formatter)
# Auto-adjust layout to fit the rotated labels
plt.gcf().autofmt_xdate()
plt.show()

What if you already have a DatetimeIndex?

If you've already set the index but still see axis issues, double-check that there are no missing or invalid datetime values in your index. You can verify this with:

# Check for non-datetime values (should return True if all are valid)
print(df.index.inferred_type == 'datetime64')
# Check for missing values in the index
print(df.index.isna().any())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:57:14