程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Summary of Python drawing color matching

編輯:Python

I treat myself python Not very satisfied with the drawing , Recently on python Draw a summary , Record the following
Refer to the following
1.https://blog.csdn.net/YMPzUELX3AIAp7Q/article/details/86746682?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-86746682-blog-100164942.pc_relevant_blogantidownloadv1&spm=1001.2101.3001.4242.1&utm_relevant_index=3

2.https://blog.csdn.net/qq_45759229/article/details/125157009
3. https://blog.csdn.net/qiu_xingye/article/details/121914314
4. https://matplotlib.org/stable/tutorials/colors/colormaps.html

brief introduction

matplotlib

matplotlib A summary of how colors are represented

Using letters ( character string ) Color ( The most commonly used )

import matplotlib.pyplot as plt
#data
x = [1, 2, 3, 4, 5]
h = 5
c = ['red', 'yellow', 'black', 'blue', 'orange']
#bar plot
plt.bar(x, height = h, color = c)
plt.show()

Use 16 Hexadecimal represents color

import matplotlib.pyplot as plt
#data
x = [1, 2, 3, 4, 5]
h = 5
## Note that the color set given here does not need to be equal to the number of points ,matplotlib Will cut itself off , however seaborn You can't do that in 
c=['#f00','#0f0','#f00','#0f0','#f00',"#f00"]
#bar plot
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
## 16 Base display color bar
#bar plot
fig=plt.figure()
colors_use=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#bcbd22', '#17becf', '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#bec1d4', '#bb7784', '#0000ff', '#111010', '#FFFF00', '#1f77b4', '#800080', '#959595',
'#7d87b9', '#bec1d4', '#d6bcc0', '#bb7784', '#8e063b', '#4a6fe3', '#8595e1', '#b5bbe3', '#e6afb9', '#e07b91', '#d33f6a', '#11c638', '#8dd593', '#c6dec7', '#ead3c6', '#f0b98d', '#ef9708', '#0fcfc0', '#9cded6', '#d5eae7', '#f3e1eb', '#f6c4e1', '#f79cd4']
plt.bar(x, height = h, color = colors_use)
plt.show()

Use a ternary array or a quaternion array to represent colors

import matplotlib.pyplot as plt
#data
x = [1, 2, 3, 4, 5]
h = 5
## Use triples to represent colors ########### RGB Pattern ###################
c=[[0.1,0.1,0.2],[0.2,0.1,0.2],[0.1,0.2,0.2],[0.8,0.1,0.2],[0.1,0.9,0.2],[0.9,0.8,0.7]]
#bar plot
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
############## RGBA Pattern , The last dimension represents transparency 
fig=plt.figure()
c=[[0.1,0.1,0.2,0.1],[0.2,0.1,0.2,0.3],[0.1,0.2,0.2,0.5],[0.8,0.1,0.2,0.7],[0.1,0.9,0.2,0.1],[0.9,0.8,0.7,0.9]]
#bar plot
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()

It means mixing

import matplotlib.pyplot as plt
#data
x = [1, 2, 3, 4, 5]
h = 5
## Note that the color set given here does not need to be equal to the number of points ,matplotlib Will cut itself off , however seaborn You can't do that in 
c=['#f00','green',[0.1,0.1,0.1],[0.2,0.9,0.9,0.6],'#f00',"#f00"]
#bar plot
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()

The above formatted color definitions are used to color chart elements , If you want to draw a more beautiful picture , Then use matplotlib Medium colormap 了

matplotlib In addition to the built-in single color , There's a lot more colormap Color , It can be understood as a color bar or gradient of multiple colors ;

matplotlib Show colormap

from matplotlib import cm
all_color_theme=dir(cm)
print(len(all_color_theme))
print(all_color_theme)
193
['Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn', 'BuGn_r', 'BuPu', 'BuPu_r', 'CMRmap', 'CMRmap_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r', 'Greens', 'Greens_r', 'Greys', 'Greys_r', 'LUTSIZE', 'MutableMapping', 'OrRd', 'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired', 'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG', 'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r', 'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy', 'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn', 'RdYlGn_r', 'Reds', 'Reds_r', 'ScalarMappable', 'Set1', 'Set1_r', 'Set2', 'Set2_r', 'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'Wistia', 'Wistia_r', 'YlGn', 'YlGnBu', 'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r', '_DeprecatedCmapDictWrapper', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_cmap_registry', '_gen_cmap_registry', '_reverser', 'afmhot', 'afmhot_r', 'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r', 'brg', 'brg_r', 'bwr', 'bwr_r', 'cbook', 'cividis', 'cividis_r', 'cmap_d', 'cmaps_listed', 'colors', 'cool', 'cool_r', 'coolwarm', 'coolwarm_r', 'copper', 'copper_r', 'cubehelix', 'cubehelix_r', 'datad', 'flag', 'flag_r', 'functools', 'get_cmap', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r', 'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r', 'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r', 'gist_yarg', 'gist_yarg_r', 'gnuplot', 'gnuplot2', 'gnuplot2_r', 'gnuplot_r', 'gray', 'gray_r', 'hot', 'hot_r', 'hsv', 'hsv_r', 'inferno', 'inferno_r', 'jet', 'jet_r', 'ma', 'magma', 'magma_r', 'mpl', 'nipy_spectral', 'nipy_spectral_r', 'np', 'ocean', 'ocean_r', 'pink', 'pink_r', 'plasma', 'plasma_r', 'prism', 'prism_r', 'rainbow', 'rainbow_r', 'register_cmap', 'revcmap', 'seismic', 'seismic_r', 'spring', 'spring_r', 'summer', 'summer_r', 'tab10', 'tab10_r', 'tab20', 'tab20_r', 'tab20b', 'tab20b_r', 'tab20c', 'tab20c_r', 'terrain', 'terrain_r', 'turbo', 'turbo_r', 'twilight', 'twilight_r', 'twilight_shifted', 'twilight_shifted_r', 'viridis', 'viridis_r', 'winter', 'winter_r']
# https://scipy-cookbook.readthedocs.io/items/Matplotlib_Show_colormaps.html
#!python
from pylab import *
from numpy import outer
rc('text', usetex=False)
a=outer(arange(0,1,0.01),ones(10))
figure(figsize=(10,5))
subplots_adjust(top=0.8,bottom=0.05,left=0.01,right=0.99)
maps=[m for m in cm.datad if not m.endswith("_r")]
maps.sort()
l=len(maps)+1
for i, m in enumerate(maps):
subplot(1,l,i+1)
axis("off")
imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower")
title(m,rotation=90,fontsize=10)
#savefig("colormaps.png",dpi=100,facecolor='gray')
print(l)
76

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def plot_colortable(colors, title, sort_colors=True, emptycols=0):
cell_width = 212
cell_height = 22
swatch_width = 48
margin = 12
topmargin = 40
# Sort colors by hue, saturation, value and name.
if sort_colors is True:
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
name)
for name, color in colors.items())
names = [name for hsv, name in by_hsv]
else:
names = list(colors)
n = len(names)
ncols = 4 - emptycols
nrows = n // ncols + int(n % ncols > 0)
width = cell_width * 4 + 2 * margin
height = cell_height * nrows + margin + topmargin
dpi = 72
fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
fig.subplots_adjust(margin/width, margin/height,
(width-margin)/width, (height-topmargin)/height)
ax.set_xlim(0, cell_width * 4)
ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
ax.yaxis.set_visible(False)
ax.xaxis.set_visible(False)
ax.set_axis_off()
ax.set_title(title, fontsize=24, loc="left", pad=10)
for i, name in enumerate(names):
row = i % nrows
col = i // nrows
y = row * cell_height
swatch_start_x = cell_width * col
swatch_end_x = cell_width * col + swatch_width
text_pos_x = cell_width * col + swatch_width + 7
ax.text(text_pos_x, y, name, fontsize=14,
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y, swatch_start_x, swatch_end_x,
color=colors[name], linewidth=18)
return fig
plot_colortable(mcolors.BASE_COLORS, "Base Colors",
sort_colors=False, emptycols=1)
plot_colortable(mcolors.TABLEAU_COLORS, "Tableau Palette",
sort_colors=False, emptycols=2)
#sphinx_gallery_thumbnail_number = 3
plot_colortable(mcolors.CSS4_COLORS, "CSS Colors")
# Optionally plot the XKCD colors (Caution: will produce large figure)
#xkcd_fig = plot_colortable(mcolors.XKCD_COLORS, "XKCD Colors")
#xkcd_fig.savefig("XKCD_Colors.png")
plt.show()


Display a single color bar

import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
n=26
m = np.zeros((1,n))
m[0]=np.linspace(0,1,n)
plt.imshow(m, cm.get_cmap("plasma"))
plt.show()
fig=plt.figure()
n=20
m = np.zeros((1,n))
m[0]=np.linspace(0,1,n)
plt.imshow(m, cm.get_cmap("Spectral"))
plt.show()
fig=plt.figure()
m = np.zeros((1,20))
for i in range(20):
m[0,i] = (i*5)/100.0
#plt.imshow(m, cmap='gray', aspect=2)
plt.imshow(m, cmap='gray')
plt.yticks(np.arange(0))
plt.xticks(np.arange(0,25,5), [0,25,50,75,100])
plt.show()

seaborn Display color bar ( Fast and convenient )

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
## matplotlib Display color bar 
fig=plt.figure()
n=26
m = np.zeros((1,n))
m[0]=np.linspace(0,1,n)
plt.imshow(m, cm.get_cmap("plasma"))
plt.show()
# seaborn Display color bar 
sns.palplot(cm.get_cmap("plasma")(m[0]))
## You can see that the color results are consistent 

matploblib Use seaborn Of palette Case study 1

import matplotlib.pyplot as plt
from matplotlib import cm
import seaborn as sns
plt.figure(dpi=50,figsize=(10,8))
N=8
palette =sns.color_palette("deep", N)
plt.bar(range(N),10,color=palette)
plt.show()

matploblib Use seaborn Of palette Case study 2


# https://stackoverflow.com/questions/37902459/seaborn-color-palette-as-matplotlib-colormap
## I want to give each dot a special color 
## 
import networkx as nx
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
fig=plt.figure()
N=8
G = nx.erdos_renyi_graph(N, 0.1)
#cmap = ListedColormap(sns.color_palette())
## Note that this must be converted into ListedColormap Images 
color_map=ListedColormap(sns.color_palette("bright"))
# about nx.draw Images ,color_map Be sure to join in range(N)
nx.draw(G, node_color=color_map(range(N)), with_labels=True,node_size=1000)
plt.show()

give the result as follows

matplotlib colormap Case study 1( Directly from the default cmap To take n Color )

https://www.freesion.com/article/7870940757/

import matplotlib.pyplot as plt
from matplotlib import cm
#plt.figure(dpi=50,figsize=(5,4))
###################### discrete # Here we need to pay attention to ,Accent Only 8 Color ####################
# Take a certain color 
fig=plt.figure()
plt.bar(range(5),5,color=plt.cm.Accent(4))
plt.show()
#ListedColormap 
# take 5 Color 
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Accent')(range(5)))
plt.show()
# take 10 Color 
N=10
fig=plt.figure(figsize=(5,4))
plt.bar(range(N),5,color=plt.get_cmap('Accent')(range(N)))
plt.show()
N=20
fig=plt.figure(figsize=(10,4))
plt.bar(range(N),5,color=plt.get_cmap('Accent')(range(N)))
plt.show()
########################## Continuous type Color ######################
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Blues')(np.linspace(0, 1, 5)))
plt.show()
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Blues')(0.8)) # Pass in a 0-1 The decimals between 
plt.show()
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Blues')(1.0))
plt.show()


matplotlib colormap Use cases 2

import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);

matploblib colormap Use cases 3

import numpy as np
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
b= np.array([6,7,8,9,10])
c = np.array([0,0,0,1,1])
plt.scatter(a,b,c=c,s=200,cmap=plt.cm.Spectral)
# c It's a value ,cmap What is retrieved is the color sequence 

matplotlib Use cases 4

plt.rcParams['figure.figsize'] = (10.0, 8.0)### Set up figure size 
# The above method is global setting , I used to use fig=plt.figure(figsize=(10,8)) Set the setting method 
x=np.linspace(-2*np.pi,2*np.pi)
y=np.sin(x)
z=np.cos(x)
#s=np.tan(x)
plt.plot(x,y,c="red") ## Common use , Or use abbreviations c="r" It's OK, too 
plt.plot(x,z,c='#1f77b4')## Set up directly 16 Hexadecimal color is also OK 
plt.plot(x,x,c=colors_use[1]) ## Use custom colors directly ,
plt.plot(x,-x,c=(0.5,0.5,0.5)) ## Use custom colors directly , Now triples represent 
for alpha in np.linspace(0.9,0.1,9):
plt.plot(x,-alpha*x,c=(0.5,0.5,0.5,alpha)) ## Of course, you can use quads to represent colors , The last dimension represents transparency , Be careful RGBA All are [0,1] Decimals of , It can't be anything else 
plt.plot(x,0.9*x,c=(0.5,0.5,0.5,0.3)) ## Use custom colors directly , Now triples represent 
plt.plot(x,np.arctan(x),c=[0.1,0.1,0.8]) ## Use custom colors directly , You can use a ternary list 
plt.show()

seaborn

View palette

https://chrisalbon.com/code/python/data_visualization/seaborn_color_palettes/

sns.palplot(sns.color_palette("deep", 10))


sns.palplot(sns.color_palette("bright", 10)) # It's really bright 

sns.palplot(sns.color_palette("dark", 10))

sns.palplot(sns.color_palette("colorblind", 10))

sns.palplot(sns.color_palette("Paired", 10))

sns.palplot(sns.color_palette("BuGn", 10))

sns.palplot(sns.color_palette("GnBu", 10))


sns.palplot(sns.color_palette("OrRd", 10))

sns.palplot(sns.color_palette("PuBu", 10))

sns.palplot(sns.color_palette("YlGn", 10))# from yellow To Green


sns.palplot(sns.color_palette("YlGnBu", 10))


sns.palplot(sns.color_palette("YlOrBr", 10))


sns.palplot(sns.color_palette("YlOrRd", 10))


sns.palplot(sns.color_palette("BrBG", 10))

sns.palplot(sns.color_palette("PiYG", 10))


sns.palplot(sns.color_palette("PRGn", 10))

sns.palplot(sns.color_palette("PuOr", 10))

sns.palplot(sns.color_palette("RdBu", 10))

sns.palplot(sns.color_palette("RdGy", 10))


sns.palplot(sns.color_palette("RdYlBu", 10))

sns.palplot(sns.color_palette("RdYlGn", 10))

sns.palplot(sns.color_palette("Spectral", 10))

sns.palplot(sns.color_palette("Reds", 10))# Remember to add s , All red 

Palette interactive view

import seaborn as sns
sns.choose_colorbrewer_palette("qualitative")
## This is very convenient , I don't have to print and check one by one 

[(0.8941176470588235, 0.10196078431372557, 0.10980392156862737),
(0.21568627450980393, 0.4941176470588236, 0.7215686274509804),
(0.3019607843137256, 0.6862745098039216, 0.29019607843137263),
(0.5960784313725492, 0.3058823529411765, 0.6392156862745098),
(1.0, 0.4980392156862745, 0.0),
(0.9999999999999998, 1.0, 0.19999999999999996),
(0.6509803921568629, 0.33725490196078434, 0.1568627450980391),
(0.9686274509803922, 0.5058823529411766, 0.7490196078431374),
(0.6, 0.6, 0.6)]
import seaborn as sns
sns.choose_dark_palette()

[(0.14135330736111978, 0.14951274600325057, 0.1481436717094509),
(0.16219560832714164, 0.18641978556477623, 0.18281574337590473),
(0.1830379092931635, 0.22332682512630186, 0.2174878150423586),
(0.204624578150829, 0.2615519732435963, 0.25339817498261435),
(0.22546687911685087, 0.29845901280512194, 0.2880702466490682),
(0.24705354797451634, 0.3366841609224164, 0.323980606589324),
(0.2678958489405382, 0.373591200483942, 0.35865267825577785),
(0.2894825177982037, 0.4118163486012364, 0.3945630381960336),
(0.3103248187642256, 0.448723388162762, 0.4292351098624875),
(0.33116711973024743, 0.4856304277242877, 0.46390718152894134)]

sns.choose_colorbrewer_palette("sequential")

[(0.9575547866205305, 0.9575547866205305, 0.9575547866205305),
(0.9012072279892349, 0.9012072279892349, 0.9012072279892349),
(0.8328950403690888, 0.8328950403690888, 0.8328950403690888),
(0.7502191464821223, 0.7502191464821223, 0.7502191464821223),
(0.6434140715109573, 0.6434140715109573, 0.6434140715109573),
(0.5387158785082661, 0.5387158785082661, 0.5387158785082661),
(0.440322952710496, 0.440322952710496, 0.440322952710496),
(0.342883506343714, 0.342883506343714, 0.342883506343714),
(0.22329873125720878, 0.22329873125720878, 0.22329873125720878),
(0.10469819300269129, 0.10469819300269129, 0.10469819300269129)]

Discrete palette

import seaborn as sns
import numpy as np
import pandas as pd
#current_pale=sns.color_palette()
#sns.palplot(current_pale)
## Color matching can be displayed 
colors_use=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#bcbd22', '#17becf', '#aec7e8', '#ffbb78', '#98df8a', '#ff9896', '#bec1d4', '#bb7784', '#0000ff', '#111010', '#FFFF00', '#1f77b4', '#800080', '#959595',
'#7d87b9', '#bec1d4', '#d6bcc0', '#bb7784', '#8e063b', '#4a6fe3', '#8595e1', '#b5bbe3', '#e6afb9', '#e07b91', '#d33f6a', '#11c638', '#8dd593', '#c6dec7', '#ead3c6', '#f0b98d', '#ef9708', '#0fcfc0', '#9cded6', '#d5eae7', '#f3e1eb', '#f6c4e1', '#f79cd4']
sns.palplot(colors_use)
#sns.palplot([colors_use[0]])# Show only the first color 

Continuous palette

sns.palplot(sns.color_palette("hls",10))
# Adjust brightness and saturation 
# hls_plaette() Function to control the brightness and saturation of the color 
# l - lightness Control the brightness 
# s - saturation Control saturation 
sns.palplot(sns.hls_palette(8,l=0.8,s=0.9))
# Pairs of colors appear 
sns.palplot(sns.color_palette('Paired'))

searborn Use palatte Case study 1( Take before n Color )

## Default color scheme 
import matplotlib.pyplot as plt
import seaborn as sns
fig=plt.figure()
current_pale=sns.color_palette()
sns.palplot(current_pale)
plt.title("current-palatte")
plt.show()
figure=plt.figure()
N=5
## Before the default color 5 Color 
color_use=[]
palette = sns.color_palette(None, N)
for i in palette:
color_use.append(i)
#print(i)
print(color_use)## Here it is 5 Color 
sns.palplot(palette) ### Use it directly palette that will do 
plt.title("palette(5)")
plt.show()
figure=plt.figure()
sns.palplot(color_use) # You can draw colors directly , In this case, I can talk to matplotlib Compare the 
plt.title("color_use")
plt.show()
[(0.12156862745098039, 0.4666666666666667, 0.7058823529411765), (1.0, 0.4980392156862745, 0.054901960784313725), (0.17254901960784313, 0.6274509803921569, 0.17254901960784313), (0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (0.5803921568627451, 0.403921568627451, 0.7411764705882353)]

seaborn Use palatte Case study 2

## Use cases 
data=np.random.normal(size=(20,8))
sns.boxplot(data=data,palette=sns.color_palette("hls",8))

seaborn Use pallete Case study 3- Color adjustment

https://www.jianshu.com/p/2961bc740614

Blue

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Blues")
plt.show()

Orange color system

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Oranges")
plt.show()

Green color system

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Greens")
plt.show()

Red color system

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Reds")
plt.show()

Purple color system

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Purples")
plt.show()

Gray color system

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Greys")
plt.show()


Other colors


import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
######## Accent Discrete tinting #####
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Accent")
plt.show()
######## A
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="RdBu")
plt.show()

Blue color optimization ( The darkest parts are black , Can you not be so deep , From light blue to dark blue )

sns.palplot(sns.color_palette("Blues", 10))
new_blues=sns.color_palette("Blues", 10)[0:7]
sns.palplot(new_blues)
# Remove the dark blue 

Light blue ( Remove the dark blue )


import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
new_blues=sns.color_palette("Blues", 10)[0:7]
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap=new_blues)
plt.show()

Light blue ( Remove the dark blue )- Refine color

# If the blue color in the above figure only takes 7 individual , You can see that the color is obviously divided into blocks , I can still make this color continuous , Just divide it into several portions 
# Then I also take 7/10 That's all right. 
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
df=pd.read_csv("/Users/xiaokangyu/Desktop/dataset/other/abalone/abalone.csv")
dfData = df.corr()
fig=plt.figure(figsize=(10,8))# If you don't set this , The picture looks small 
new_blues=sns.color_palette("Blues", 1000)[0:700]
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap=new_blues)
plt.show()

seaborn Custom palette

flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui) ## Set up the palette 
sns.palplot(sns.color_palette())
sns.palplot(flatui)#

boxplot Use the custom palette

data=np.random.normal(size=(20,6))
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui) # Using this palette ,
#print(sns.palplot(sns.color_palette()))
sns.boxplot(data=data)# snsborn This can directly manipulate the matrix , There is no need to operate dataframe So complicated 
sns.palplot(sns.color_palette())# You can see , Color correspondence is consistent 


barplot Use the custom palette

# seaborn It doesn't have to be done directly dataframe, You can directly manipulate the list 
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui) # Using this palette ,
x=["one","two","three"]# This can also be drawn directly 
y=[10,10,10]
sns.barplot(x=x,y=y)
# You can see that the use of this color is consistent with the previous use 
sns.palplot(sns.color_palette())# You can see , Color correspondence is consistent 

scatterplot Use the custom palette

fig=plt.figure()
x=np.array([[1,1],[2,2],[3,3],[4,4],[5,5]])
## sns Set up your own palette
sns.scatterplot(x=x[:,0],y=x[:,1],s=1000,hue=x[:,0],palette=["red","blue","green","pink","yellow"])
plt.show()
fig=plt.figure()
x=np.array([[1,1],[2,2],[3,3],[4,4],[5,5]])
## sns Set up your own palette, This is also possible . Note that here you can set sns My palette , But you still have to call it explicitly 
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c",[0.1,0.5,0.5]] # The number of this color and hue The number of colors must be consistent 
sns.scatterplot(x=x[:,0],y=x[:,1],s=1000,hue=x[:,0],palette=flatui)
plt.show()


palettable

import palettable
from palettable.cartocolors.qualitative import Bold_9
Bold_9.show_discrete_image()#Bold_9 Various color bar pictures 
print(Bold_9.colors)#Bold_9 colormap Of each color in RGB Format color number 
print(Bold_9.hex_colors)#Bold_9 colormap Of each color in hex Format color number 
print(Bold_9.mpl_colors)#RGB tuples in the range 0-1 as used by matplotlib


[[127, 60, 141], [17, 165, 121], [57, 105, 172], [242, 183, 1], [231, 63, 116], [128, 186, 90], [230, 131, 16], [0, 134, 149], [207, 28, 144]]
['#7F3C8D', '#11A579', '#3969AC', '#F2B701', '#E73F74', '#80BA5A', '#E68310', '#008695', '#CF1C90']
[(0.4980392156862745, 0.23529411764705882, 0.5529411764705883), (0.06666666666666667, 0.6470588235294118, 0.4745098039215686), (0.2235294117647059, 0.4117647058823529, 0.6745098039215687), (0.9490196078431372, 0.7176470588235294, 0.00392156862745098), (0.9058823529411765, 0.24705882352941178, 0.4549019607843137), (0.5019607843137255, 0.7294117647058823, 0.35294117647058826), (0.9019607843137255, 0.5137254901960784, 0.06274509803921569), (0.0, 0.5254901960784314, 0.5843137254901961), (0.8117647058823529, 0.10980392156862745, 0.5647058823529412)]

paletable Use cases 1

import matplotlib.pyplot as plt
import matplotlib as mpl
import palettable
mpl.rc_file_defaults()
my_dpi = 96
plt.figure(figsize=(580 / my_dpi, 580 / my_dpi), dpi=my_dpi)
plt.subplot(221)
patches, texts, autotexts = plt.pie(
x=[1, 2, 3],
labels=['A', 'B', 'C'],
# Use palettable.tableau.BlueRed_6
colors=palettable.tableau.BlueRed_6.mpl_colors[0:3],
autopct='%.2f%%',
explode=(0.1, 0, 0))
patches[0].set_alpha(0.3)
patches[2].set_hatch('|')
patches[1].set_hatch('x')
plt.title('tableau.BlueRed_6', size=12)
mpl.rc_file_defaults()
plt.subplot(222)
patches, texts, autotexts = plt.pie(
x=[1, 2, 3],
labels=['A', 'B', 'C'],
# Use palettable.cartocolors.qualitative.Bold_9
colors=palettable.cartocolors.qualitative.Bold_9.mpl_colors[0:3],
autopct='%.2f%%',
explode=(0.1, 0, 0))
patches[0].set_alpha(0.3)
patches[2].set_hatch('|')
patches[1].set_hatch('x')
plt.title('cartocolors.qualitative.Bold_9', size=12)
mpl.rc_file_defaults()
plt.subplot(223)
patches, texts, autotexts = plt.pie(
x=[1, 2, 3],
labels=['A', 'B', 'C'],
# Use palettable.cartocolors.qualitative.Bold_9
colors=palettable.cartocolors.qualitative.Bold_9.mpl_colors[0:3],
autopct='%.2f%%',
explode=(0.1, 0, 0))
patches[0].set_alpha(0.3)
patches[2].set_hatch('|')
patches[1].set_hatch('x')
plt.title('cartocolors.qualitative.Bold_9', size=12)
plt.subplot(223)
patches, texts, autotexts = plt.pie(
x=[1, 2, 3],
labels=['A', 'B', 'C'],
# Use palettable.lightbartlein.sequential.Blues10_5
colors=palettable.lightbartlein.sequential.Blues10_5.mpl_colors[0:3],
autopct='%.2f%%',
explode=(0.1, 0, 0))
#matplotlib.patches.Wedge
patches[0].set_alpha(0.3)
patches[2].set_hatch('|')
patches[1].set_hatch('x')
plt.title('lightbartlein.sequential.Blues10_5', size=12)
plt.subplot(224)
patches, texts, autotexts = plt.pie(
x=[1, 2, 3],
labels=['A', 'B', 'C'],
colors=palettable.wesanderson.Moonrise5_6.mpl_colors[0:3],
autopct='%.2f%%',
explode=(0.1, 0, 0))
patches[0].set_alpha(0.3)
patches[2].set_hatch('|')
patches[1].set_hatch('x')
plt.title('wesanderson.Moonrise5_6', size=12)
plt.show()

palettable Use cases 2

import seaborn as sns
iris_sns = sns.load_dataset("iris")
import palettable
g = sns.pairplot(
iris_sns,
hue='species',
palette=palettable.tableau.TrafficLight_9.mpl_colors[0:3], #Matplotlib Color 
)
sns.set(style='whitegrid')
g.fig.set_size_inches(10, 8)
sns.set(style='whitegrid', font_scale=1.5)

network Display node color

import networkx as nx
fig=plt.figure()
G = nx.erdos_renyi_graph(20, 0.1)
color_map = []
for node in G:
if node < 10:
color_map.append("yellow")
else:
color_map.append('red')
nx.draw(G, node_color=color_map, with_labels=True)
plt.show()
## I want to give each dot a special color 
import networkx as nx
fig=plt.figure()
G = nx.erdos_renyi_graph(8, 0.1)
## Note that you can't use it directly here 
# color_map= plt.cm.get_cmap("Accent"), Asking for is float perhaps string
color_map = plt.cm.get_cmap("Accent")(range(8))## So what we get here is float
print(color_map)
nx.draw(G, node_color=color_map, with_labels=True)
plt.show()

[[0.49803922 0.78823529 0.49803922 1. ]
[0.74509804 0.68235294 0.83137255 1. ]
[0.99215686 0.75294118 0.5254902 1. ]
[1. 1. 0.6 1. ]
[0.21960784 0.42352941 0.69019608 1. ]
[0.94117647 0.00784314 0.49803922 1. ]
[0.74901961 0.35686275 0.09019608 1. ]
[0.4 0.4 0.4 1. ]]


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved