Python 3.6基础绘图问题:如何将Adj Close与Date关联绘图
Hey there! No stress about rusty Python skills—this is a super common gotcha with pandas plotting, and we can fix it in a couple of easy ways. Let's break down your options:
1. Directly Specify X and Y Columns (Simplest Method)
Instead of calling .plot() on just the Adj Close series, use the full DataFrame's plot method and explicitly tell pandas which columns to use for x and y axes. This skips relying on the index entirely:
bp.plot(x='Date', y='Adj Close', label='BP', figsize=(16,8), title='Adjusted Closing Price')
This will immediately set your Date column as the horizontal axis and Adj Close as the vertical one—exactly what you want.
2. Ensure Your Date Column is Properly Formatted (Optional but Recommended)
If your Date column is stored as plain text (check with bp['Date'].dtype—if it says object, that's strings), converting it to a datetime type will make your plot's axis labels way cleaner (like showing proper date ranges instead of messy strings):
import pandas as pd # Convert Date column to datetime bp['Date'] = pd.to_datetime(bp['Date']) # Now plot using the method above bp.plot(x='Date', y='Adj Close', label='BP', figsize=(16,8), title='Adjusted Closing Price')
3. Set Date as the Index (Alternative Approach)
If you prefer to work with the date as your DataFrame's index (which is common for time-series data), you can reindex your DataFrame first:
# Option 1: Modify the original DataFrame bp.set_index('Date', inplace=True) bp['Adj Close'].plot(label='BP', figsize=(16,8), title='Adjusted Closing Price') # Option 2: Keep original DataFrame intact (no inplace change) bp.set_index('Date')['Adj Close'].plot(label='BP', figsize=(16,8), title='Adjusted Closing Price')
Just note that inplace=True will change your original DataFrame, so use that only if you don't need the old index anymore.
Any of these methods should get you the plot you're after. Start with the first one—it's the quickest fix, and you can add the datetime conversion if your axis labels look wonky!
内容的提问来源于stack exchange,提问作者MRL

