我对自己python画的图不是很满意,最近对python画图做了一个总结,记录如下 参考如下 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
简介
matplotlib
matplotlib表示颜色的方式总结
使用字母(字符串)表示颜色(最常用)
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
h = 5
c = ['red', 'yellow', 'black', 'blue', 'orange']
plt.bar(x, height = h, color = c)
plt.show()
?
?
使用16进制表示颜色
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
h = 5
c=['#f00','#0f0','#f00','#0f0','#f00',"#f00"]
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
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()
?
使用三元数组或者四元数组表示颜色
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
h = 5
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]]
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
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]]
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
?
混合表示
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
h = 5
c=['#f00','green',[0.1,0.1,0.1],[0.2,0.9,0.9,0.6],'#f00',"#f00"]
fig=plt.figure()
plt.bar(x, height = h, color = c)
plt.show()
?
上面使用的格式化的颜色定义给图表元素配色,如果想画出更加美观的图,那么就要使用matplotlib中的colormap了
matplotlib除了内置单颜色,还有大量colormap颜色,可以理解为多种颜色合在一起的颜色条或者渐变色;
matplotlib显示 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']
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)
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
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)
plot_colortable(mcolors.CSS4_COLORS, "CSS Colors")
plt.show()
?
?
显示单个颜色条
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')
plt.yticks(np.arange(0))
plt.xticks(np.arange(0,25,5), [0,25,50,75,100])
plt.show()
?
seaborn显示颜色条(快捷方便)
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
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()
sns.palplot(cm.get_cmap("plasma")(m[0]))
?
matploblib使用seaborn的palette 案例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使用seaborn的palette 案例2
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)
color_map=ListedColormap(sns.color_palette("bright"))
nx.draw(G, node_color=color_map(range(N)), with_labels=True,node_size=1000)
plt.show()
结果如下
?
?
matplotlib colormap案例1(直接从默认的cmap中取n种颜色)
https://www.freesion.com/article/7870940757/
import matplotlib.pyplot as plt
from matplotlib import cm
fig=plt.figure()
plt.bar(range(5),5,color=plt.cm.Accent(4))
plt.show()
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Accent')(range(5)))
plt.show()
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()
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))
plt.show()
fig=plt.figure()
plt.bar(range(5),5,color=plt.get_cmap('Blues')(1.0))
plt.show()
?
matplotlib colormap使用案例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
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使用案例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)
matplotlib 使用案例4
plt.rcParams['figure.figsize'] = (10.0, 8.0)
x=np.linspace(-2*np.pi,2*np.pi)
y=np.sin(x)
z=np.cos(x)
plt.plot(x,y,c="red")
plt.plot(x,z,c='#1f77b4')
plt.plot(x,x,c=colors_use[1])
plt.plot(x,-x,c=(0.5,0.5,0.5))
for alpha in np.linspace(0.9,0.1,9):
plt.plot(x,-alpha*x,c=(0.5,0.5,0.5,alpha))
plt.plot(x,0.9*x,c=(0.5,0.5,0.5,0.3))
plt.plot(x,np.arctan(x),c=[0.1,0.1,0.8])
plt.show()
?
?
seaborn
查看调色板
https://chrisalbon.com/code/python/data_visualization/seaborn_color_palettes/
sns.palplot(sns.color_palette("deep", 10))
?
?
sns.palplot(sns.color_palette("bright", 10))
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))
?
?
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))
?
?
调色板交互方式查看
import seaborn as sns
sns.choose_colorbrewer_palette("qualitative")
[(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)]
?
离散型调色板
import seaborn as sns
import numpy as np
import pandas as pd
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(sns.color_palette("hls",10))
sns.palplot(sns.hls_palette(8,l=0.8,s=0.9))
sns.palplot(sns.color_palette('Paired'))
?
searborn 使用palatte案例1(取前n种颜色)
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
color_use=[]
palette = sns.color_palette(None, N)
for i in palette:
color_use.append(i)
print(color_use)
sns.palplot(palette)
plt.title("palette(5)")
plt.show()
figure=plt.figure()
sns.palplot(color_use)
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 使用palatte案例2
data=np.random.normal(size=(20,8))
sns.boxplot(data=data,palette=sns.color_palette("hls",8))
seaborn使用pallete案例3-色系调整
https://www.jianshu.com/p/2961bc740614
蓝色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Blues")
plt.show()
?
?
橙色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Oranges")
plt.show()
?
?
绿色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Greens")
plt.show()
?
?
红色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Reds")
plt.show()
?
紫色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Purples")
plt.show()
?
灰色色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Greys")
plt.show()
? ?
其他色系
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))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="Accent")
plt.show()
fig=plt.figure(figsize=(10,8))
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap="RdBu")
plt.show()
?
蓝色色系优化(颜色最深的地方都成黑色了,能不能不要那么深,从浅蓝到深蓝就可以了)
sns.palplot(sns.color_palette("Blues", 10))
new_blues=sns.color_palette("Blues", 10)[0:7]
sns.palplot(new_blues)
浅蓝色系(去掉深蓝)
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))
new_blues=sns.color_palette("Blues", 10)[0:7]
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap=new_blues)
plt.show()
?
浅蓝色系(去掉深蓝)-细化颜色
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))
new_blues=sns.color_palette("Blues", 1000)[0:700]
sns.heatmap(dfData, annot=True, vmax=1, square=True, cmap=new_blues)
plt.show()
?
seaborn自定义调色板
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui)
sns.palplot(sns.color_palette())
sns.palplot(flatui)
?
boxplot使用自定义调色板
data=np.random.normal(size=(20,6))
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui)
sns.boxplot(data=data)
sns.palplot(sns.color_palette())
?
barplot使用自定义调色板
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
sns.set_palette(flatui)
x=["one","two","three"]
y=[10,10,10]
sns.barplot(x=x,y=y)
sns.palplot(sns.color_palette())
scatterplot使用自定义调色板
fig=plt.figure()
x=np.array([[1,1],[2,2],[3,3],[4,4],[5,5]])
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]])
flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c",[0.1,0.5,0.5]]
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()
print(Bold_9.colors)
print(Bold_9.hex_colors)
print(Bold_9.mpl_colors)
?
?
[[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使用案例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'],
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'],
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'],
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'],
colors=palettable.lightbartlein.sequential.Blues10_5.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('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使用案例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],
)
sns.set(style='whitegrid')
g.fig.set_size_inches(10, 8)
sns.set(style='whitegrid', font_scale=1.5)
?
network 显示节点颜色
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()
import networkx as nx
fig=plt.figure()
G = nx.erdos_renyi_graph(8, 0.1)
color_map = plt.cm.get_cmap("Accent")(range(8))
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. ]]
python颜色与R的颜色的联系
我现在想做这么一件事,就是我想将R中的颜色转换成python中的颜色使用 https://zhuanlan.zhihu.com/p/30407500
预备知识
colors()
结果如下 可以看到R中有很多字符串命名的颜色,并不是只有“red",“green”,"blue"之列的, 总共有657种 首先使用col2rgb 函数将字符串颜色转成rgb
col2rgb(c("cyan4","wheat"))
结果如下
显示R中字符串颜色
color_used <- c(
"cyan4","skyblue3","darkolivegreen3","lightpink","darkmagenta","brown","blueviolet","bisque4",
"deeppink3", "darkkhaki",
"dodgerblue4", "goldenrod4", "gainsboro", "firebrick4", "cadetblue3",
"greenyellow", "gray6", "coral2", "yellow4",
"darkgoldenrod3", "navy", "deepskyblue3","antiquewhite3"
)
image(1:length(color_used),1, as.matrix(1:length(color_used)),col=color_used,xlab = "", ylab = "")
结果如下
R颜色转换成16进制
color_used <- c(
"cyan4","skyblue3","darkolivegreen3","lightpink","darkmagenta","brown","blueviolet","bisque4",
"deeppink3", "darkkhaki",
"dodgerblue4", "goldenrod4", "gainsboro", "firebrick4", "cadetblue3",
"greenyellow", "gray6", "coral2", "yellow4",
"darkgoldenrod3", "navy", "deepskyblue3","antiquewhite3"
)
hex_color_pal <- colorRampPalette(color_used)
hex_color=hex_color_pal(23)
hex_color
结果如下 存储结果
save(hex_color,file="hex_color.RData")
python中使用R中的颜色
方案1
import pyreadr
result=pyreadr.read_r("hex_color.RData")
color_used=list(result["hex_color"]["hex_color"].values)
import seaborn as sns
sns.palplot(color_used)
结果如下
方案2
%load_ext rpy2.ipython
%%R -o hex_color_python
color_used <- c(
"cyan4","skyblue3","darkolivegreen3","lightpink","darkmagenta","brown","blueviolet","bisque4",
"deeppink3", "darkkhaki",
"dodgerblue4", "goldenrod4", "gainsboro", "firebrick4", "cadetblue3",
"greenyellow", "gray6", "coral2", "yellow4",
"darkgoldenrod3", "navy", "deepskyblue3","antiquewhite3"
)
image(1:length(color_used),1, as.matrix(1:length(color_used)),col=color_used,xlab = "", ylab = "")
hex_color_pal <- colorRampPalette(color_used)
color_num=length(color_used)
hex_color_python=hex_color_pal(color_num)
结果如下 可以看到python中的颜色和R中的颜色是一致的
palette转换成十六进制
import seaborn as sns
sns.palplot(sns.color_palette('Blues',10))
color_blue=sns.color_palette('Blues',10)
color_blue
|