使用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):
| Date | Open | High | Low | Close | Volume | Market Cap |
|---|---|---|---|---|---|---|
| Apr 09, 2018 | 7044.32 | 7178.11 | 6661.99 | 6770.73 | 4894060000 | 119516000000 |
| Apr 08, 2018 | 6919.98 | 7111.56 | 6919.98 | 7023.52 | 3652500000 | 117392000000 |
| Apr 07, 2018 | 6630.51 | 7050.54 | 6630.51 | 6911.09 | 3976610000 | 112467000000 |
| Apr 06, 2018 | 6815.96 | 6857.49 | 6575.00 | 6636.32 | 3766810000 | 115601000000 |
| Apr 05, 2018 | 6848.65 | 6933.82 | 6644.80 | 6811.47 | 5639320000 | 116142000000 |
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

