Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color palette for stackplot, matplotlib?

I hope to change the color palette for stackplot so that the large area has a light color, the smaller area has a bright color.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
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
dat1 = pd.read_csv(file)
dat2 = dat1.iloc[:,0:12]
Year = dat2.iloc[:,0]
Mud = dat2.iloc[:,1:12]
Mud = Mud/1000.0

#read columns of dataframe
vol = Mud.columns

#transpose mud
mud2 = Mud.T


%matplotlib qt5

#set size of figure
fig, ax = plt.subplots()
fig.set_size_inches(15, 7.5)

#read values of dataframe
value = mud2.values
#plot stack area
sp = ax.stackplot(Year, value)
#set legend
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)

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 fig: run this code before show()
plt.savefig(r"E:\FD\Barren_Mudflat\ChinaCoastal\Provinces\stackplot.jpg", 
dpi = 600)
plt.show()

This is the result of the code. I hope to change the red into a light color, but I don't know how to change the default color pallete.

like image 462
Xinxin Avatar asked Sep 05 '26 06:09

Xinxin


2 Answers

For anyone like me finding this thread somewhat later than creation.

It is possible to set custom colors by HEX color codes.

E.g.

color_map = ["#9b59b6", "#e74c3c", "#34495e", "#2ecc71"]

Then plot:

ax.stackplot(x, y, colors = color_map)

As a last note it is also possible to convert RGB colors to HEX colors (which I had to do in my case). As follows:

rgb_code = [128, 128, 128]
hex_color = '#%02x%02x%02x' % (rgb_code[0], rgb_code[1], rgb_code[2])
like image 195
user1455613 Avatar answered Sep 06 '26 20:09

user1455613


col = sns.color_palette("hls", 11)
sp = ax.stackplot(Year, value, colors = col)
like image 27
Xinxin Avatar answered Sep 06 '26 19:09

Xinxin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!