如何修改Matplotlib中stackplot的配色:大区域浅色小区域亮色
Hey there! I see you want to tweak your stackplot's color scheme so larger mudflat areas use lighter colors, while smaller ones get brighter tones. Let's fix this by adding a bit of logic to calculate each region's total area, sort them by size, and then assign colors that match your requirement. Here's the modified code and breakdown:
The core idea is to first calculate the total area of each province, sort them by their total size, then map lighter colors to larger areas and brighter ones to smaller ones.
Step-by-Step Breakdown
- Calculate total area per province: Sum up the yearly area values for each column (each province) to get their total size over the years.
- Sort provinces by total area: Reorder the provinces from largest to smallest so we can align colors correctly with area size.
- Generate a gradient color palette: Use Seaborn to create a color range that shifts from light to bright, matching our sorted province list.
- Reorder data and plot: Feed the sorted data and custom colors into
stackplotto get the desired visual effect.
Modified Full Code
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import matplotlib as mpl import matplotlib.font_manager as font_manager file = r'E:\FD\Barren_Mudflat\ChinaCoastal\Provinces\0ProvinceStat.csv' # Set font property of legend font1 = {'family' : 'Times New Roman', 'weight' : 'normal', 'size' : 16 } # Read csv data dat1 = pd.read_csv(file) dat2 = dat1.iloc[:,0:12] Year = dat2.iloc[:,0] Mud = dat2.iloc[:,1:12] Mud = Mud/1000.0 # -------------------------- New Coloring Logic -------------------------- # 1. Calculate total area for each province (sum across years) total_area_per_province = Mud.sum(axis=0) # 2. Sort provinces from largest total area to smallest sorted_provinces = total_area_per_province.sort_values(ascending=False).index # 3. Generate color palette: lighter for larger areas, brighter for smaller # Using reversed Blues palette (light to dark/bright) - swap to "Blues" if you want opposite logic colors = sns.color_palette("Blues_r", n_colors=len(sorted_provinces)) # 4. Reorder the data to match our sorted province list sorted_mud_data = Mud[sorted_provinces] value = sorted_mud_data.T.values # ------------------------------------------------------------------- # Update column names to sorted list vol = sorted_provinces %matplotlib qt5 # Set figure size fig, ax = plt.subplots() fig.set_size_inches(15, 7.5) # Plot stackplot with custom colors sp = ax.stackplot(Year, value, colors=colors) # Create legend proxies proxy = [mpl.patches.Rectangle((0,0), 0,0, facecolor=pol.get_facecolor()[0]) for pol in sp] ax.legend(proxy, vol, prop=font1, loc='upper left', bbox_to_anchor=(0.01,1), ncol=6) # Axis settings plt.xlim(1986,2016) plt.xticks([1986,1991,1996,2001,2006,2011,2016], fontproperties='Times New Roman', size='16') plt.xlabel('Year', fontproperties='Times New Roman', size='18') plt.ylim(0,1400) plt.yticks(np.arange(0,1500,200), fontproperties='Times New Roman', size='16') plt.ylabel('Mudflat area (thousand ha)', fontproperties='Times New Roman', size='18') # Save figure before showing plt.savefig(r"E:\FD\Barren_Mudflat\ChinaCoastal\Provinces\stackplot.jpg", dpi=600) plt.show()
Quick Notes
- Palette Choice: I used
sns.color_palette("Blues_r")here — the_rreverses the default Blues palette, so the largest area gets the lightest blue, and the smallest gets the darkest (brightest) blue. If you prefer a different color scheme, swap"Blues_r"for"Greens_r","Oranges_r", or any other Seaborn palette name. - Reverse the Logic: If you ever want smaller areas to use lighter colors instead, just change
ascending=Falsetoascending=Truein thesort_valuesline, and remove the_rfrom the palette name (e.g., use"Blues"instead of"Blues_r"). - Color Matching: The
n_colorsparameter ensures we get exactly enough colors for all your provinces, so no mismatches here.
This change will make your previously red (large) area show up as a light shade, while smaller areas take on brighter, more saturated colors — exactly what you wanted!
内容的提问来源于stack exchange,提问作者Xinxin

