如何在pandas/matplotlib折线图中单独设置2020年线条宽度?
Unfortunately, you can’t pull this off with that single line of code— the lw (or linewidth) parameter in pandas' plot() method applies the same line width to all series being plotted. To highlight the 2020 line, you’ll need to either plot each year’s data separately or tweak the line properties after the initial plot.
Here are two straightforward, practical methods:
Method 1: Plot each series individually
Loop through each year column in your DataFrame, setting a thicker linewidth exclusively for 2020:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(20,12)) # Iterate over each year column for year in ice_data_dates.columns: # Thicken the line only for 2020 line_width = 5 if year == '2020' else 3 ice_data_dates[year].plot(ax=ax, lw=line_width, label=year) # Apply your original plot customizations ax.set_title('Arctic Sea Ice Extent', fontsize=16) ax.tick_params(axis='both', labelsize=16) ax.grid(True) ax.legend(fontsize=16) plt.show()
Method 2: Adjust line properties after initial plot
Plot all lines first with your default settings, then target the 2020 line to make it thicker:
fig, ax = plt.subplots(figsize=(20,12)) # Run your original plot command ice_data_dates.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=3, fontsize=16, ax=ax, grid=True) # Find the 2020 line and update its width for line in ax.lines: if line.get_label() == '2020': line.set_linewidth(5) # Refresh the legend to reflect the thicker line (optional but clean) ax.legend(fontsize=16) plt.show()
Both approaches will make the 2020 line stand out while keeping the rest of your plot aligned with your original setup. The first method gives you full granular control over each line’s properties, while the second is faster if you only need to adjust one series.
内容的提问来源于stack exchange,提问作者Eli Turasky

