如何将Pandas绘图的X轴刻度标签改为01 Jan格式
01 Jan Format for Your Arctic Sea Ice Plot No problem at all—let's get those X-axis labels looking exactly how you want. The key is converting your existing mm-dd index strings into datetime objects first, then formatting them with strftime() (either by modifying the DataFrame index directly, or just adjusting the plot ticks without altering your original data). Here are two straightforward approaches:
Approach 1: Modify the DataFrame Index Permanently
This changes your index to the dd Mmm format for good, so every time you plot, the labels will be correct by default:
import pandas as pd import matplotlib.pyplot as plt # Recreate your sample DataFrame (skip this if you already have your data loaded) data = { "2011": [12.896, 12.915, 12.926, 13.051, 13.176], "2012": [13.353, 13.421, 13.379, 13.414, 13.417], "2013": [12.959, 12.961, 13.012, 13.045, 13.065], "2014": [13.011, 13.103, 13.116, 13.219, 13.148], "2015": [13.073, 13.125, 13.112, 13.051, 13.115], "2016": [12.721, 12.806, 12.790, 12.829, 12.874], "2017": [12.643, 12.644, 12.713, 12.954, 12.956], "2018": [12.484, 12.600, 12.634, 12.724, 12.834], "2019": [12.876, 12.956, 12.959, 13.047, 13.098], "2020": [13.102, 13.075, 13.176, 13.187, 13.123] } ice_data = pd.DataFrame(data, index=["01-01", "01-02", "01-03", "01-04", "01-05"]) # Step 1: Convert string index ("mm-dd") to datetime objects ice_data.index = pd.to_datetime(ice_data.index, format="%m-%d") # Step 2: Format datetime index to "dd Mmm" (e.g., "01 Jan") ice_data.index = ice_data.index.strftime("%d %b") # Plot as usual fig, ax = plt.subplots() ice_data.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=4, fontsize=16, ax=ax, grid=True) plt.show()
Approach 2: Adjust Plot Ticks Without Changing Your Data
If you want to keep your original DataFrame intact, just format the tick labels directly in the plot:
import pandas as pd import matplotlib.pyplot as plt # Use your existing ice_data DataFrame here fig, ax = plt.subplots() ice_data.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=4, fontsize=16, ax=ax, grid=True) # Convert index strings to datetime, then format for ticks dt_index = pd.to_datetime(ice_data.index, format="%m-%d") ax.set_xticklabels(dt_index.strftime("%d %b"), fontsize=16) plt.show()
Quick Breakdown of the Formatting Codes:
%d: Returns the two-digit day (01, 02, etc.)%b: Returns the abbreviated month name (Jan, Feb, Mar—this adapts to your system's default language automatically)- Specifying
format="%m-%d"inpd.to_datetime()ensures pandas parses your date strings correctly, avoiding unexpected errors.
Either method will give you the clean 01 Jan style labels on your X-axis!
内容的提问来源于stack exchange,提问作者Eli Turasky

