Matplotlib图表无法显示日期问题求助(附实现代码)
Hey there! Let's work through that problem where your Matplotlib charts aren't showing dates properly. Based on your code snippet, here are the most common fixes to get those dates rendering correctly:
1. Ensure your date data is in proper datetime format
Chances are, when you load the Excel file, year columns (like 1980, 1981) are being treated as strings or integers instead of date objects. Pandas makes it easy to convert these to valid datetime types:
# After loading and cleaning your data # Assume we transpose data to make years the index years = list(map(str, range(1980, 2014))) # Adjust range to match your dataset df_can_t = df_can.set_index('OdName')[years].transpose() # Convert index to datetime format df_can_t.index = pd.to_datetime(df_can_t.index, format='%Y')
Verify the conversion worked with print(df_can_t.index.dtype) — it should return datetime64[ns].
2. Configure Matplotlib's date formatter and locator
Even with datetime data, Matplotlib might not auto-format the x-axis nicely. Use matplotlib.dates tools to control date display:
import matplotlib.dates as mdates # After creating your plot ax = plt.gca() # Get the current plot axis # Set date display format (e.g., full year like 2000) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) # Set how often dates appear (e.g., every 5 years) ax.xaxis.set_major_locator(mdates.YearLocator(5)) # Rotate x-axis labels to avoid overlap plt.xticks(rotation=45) # Adjust layout to prevent label cutoff plt.tight_layout()
3. Double-check your plotting data
When calling plot(), make sure you're passing the datetime index as your x-axis data. For example, plotting immigration from China:
df_can_t['China'].plot(kind='line') plt.title('Immigration from China to Canada') plt.xlabel('Year') plt.ylabel('Number of Immigrants')
Since df_can_t.index is datetime, Matplotlib will recognize it as date data instead of generic numbers.
Full Working Example
Here's how all this fits into your existing code:
import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.dates as mdates import pandas as pd import numpy as np df_can = pd.read_excel('Canada.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20), skip_footer=2) def data_format(df_can): # Drop unnecessary columns df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True) # Rename country column for clarity df_can.rename(columns={'OdName': 'Country'}, inplace=True) return df_can df_can_clean = data_format(df_can) # Prepare date-focused data years = list(map(str, range(1980, 2014))) df_can_t = df_can_clean.set_index('Country')[years].transpose() df_can_t.index = pd.to_datetime(df_can_t.index, format='%Y') # Create and format the plot df_can_t['China'].plot(kind='line', figsize=(10, 6)) plt.title('Immigration from China to Canada (1980-2013)') plt.xlabel('Year') plt.ylabel('Number of Immigrants') # Apply date formatting ax = plt.gca() ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) ax.xaxis.set_major_locator(mdates.YearLocator(5)) plt.xticks(rotation=45) plt.tight_layout() plt.show()
If you still hit issues, check that your Excel file's year columns are correctly named (no typos!) and that the datetime conversion didn't fail (look for NaT values with df_can_t.index.isna().sum()).
内容的提问来源于stack exchange,提问作者Isaac Rivera

