1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Task5:第五回:样式色彩秀芳华

Task5:第五回:样式色彩秀芳华

时间:2023-04-01 19:35:32

相关推荐

Task5:第五回:样式色彩秀芳华

样式色彩秀芳华

1、matplotlib的绘图样式(style)1.1、matplotlib预先定义样式1.2、用户自定义stylesheet1.3、设置rcparams1.4、修改 matplotlibrc2、matplotlib的色彩设置(color)2.1、RGB或RGBA2.2、HEX RGB 或 RGBA2.3、灰度色阶2.4、单字符基本颜色2.5、颜色名称2.6、使用colormap设置一组颜色2.6.1、顺序(Sequential)2.6.2、发散(Diverging)2.6.3、循环(Cyclic)2.6.4、定性(Qualitative)2.6.5、杂色(Miscellaneous)3、思考题3.1、使用 LinearSegmentedColormap 的 from_list 方法创建 colormap3.2、使用 ListedColormap 自定义 colormap

教程来源:https://datawhalechina.github.io/fantastic-matplotlib

参考资料:

1、Python数据可视化matplotlib:第五回:样式色彩秀芳华_林遠夏的博客-程序员秘密:https://url.cy/wryWK2

2、学会这6个可视化配色基本技巧,还原数据本身的意义:/p/88892542

3、RGB颜色和HEX颜色之间是可以一一对应的,以下网址提供了两种色彩表示方法的转换工具:/

4、[matplotlib] 颜色设置及Matplotlib颜色对照表:/p/65220518

5、matplotlib基本颜色演示:.cn/gallery/color/color_demo.html

6、五种colormap的字符串表示和颜色图的对应关系:/stable/tutorials/colors/colormaps.html

7、rcParam支持的参数列表可以参照官方文档的相关说明:

/stable/api/matplotlib_configuration_api.html?highlight=rcparams#matplotlib.rcParams

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as np

详细介绍matplotlib中样式和颜色的使用。

绘图样式和颜色是丰富可视化图表的重要手段,因此熟练掌握本章可以让可视化图表变得更美观,突出重点和凸显艺术性。

关于绘图样式,常见的有3种方法,分别是修改预定义样式,自定义样式和rcparams。

关于颜色使用,本章介绍了常见的5种表示单色颜色的基本方法,以及colormap多色显示的方法。

1、matplotlib的绘图样式(style)

在matplotlib中,要想设置绘制样式,最简单的方法是在绘制元素时单独设置样式。

但是有时候,当用户在做专题报告时,往往会希望保持整体风格的统一而不用对每张图一张张修改,因此matplotlib库还提供了四种批量修改全局样式的方式

1.1、matplotlib预先定义样式

matplotlib贴心地提供了许多内置的样式供用户使用,使用方法很简单,只需在python脚本的最开始输入想使用style的名称即可调用,尝试调用不同内置样式,比较区别

matplotlib究竟内置了那些样式供使用呢?总共以下26种丰富的样式可供选择,如下:

# 默认样式plt.style.use('default')plt.plot([1,2,3,4],[2,3,4,5]);

plt.style.use('ggplot')plt.plot([1,2,3,4],[2,3,4,5]);

print(plt.style.available)len(plt.style.available)

['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']28

# 绘制所有风格图fig = plt.figure(figsize = (60, 30))for i in range(len(plt.style.available)):plt.subplot(4, 7, i+1)plt.title(plt.style.available[i],fontsize=50,color='k')plt.style.use(plt.style.available[i])plt.plot([1,2,3,4],[2,3,4,5])fig.suptitle('style',fontsize=100, color='b',fontweight='bold')plt.tight_layout()plt.show()

1.2、用户自定义stylesheet

在任意路径下创建一个后缀名为mplstyle的样式清单,编辑文件添加以下样式内容:

axes.titlesize : 24

axes.labelsize : 20

lines.linewidth : 3

lines.markersize : 10

xtick.labelsize : 16

ytick.labelsize : 16

# 引用自定义stylesheet后观察图表变化。plt.style.use('presentation.mplstyle')plt.plot([1,2,3,4],[2,3,4,5]);

# 值得特别注意的是,matplotlib支持混合样式的引用,只需在引用时输入一个样式列表,若是几个样式中涉及到同一个参数,右边的样式表会覆盖左边的值。plt.style.use(['dark_background', 'presentation.mplstyle'])plt.plot([1,2,3,4],[2,3,4,5]);

1.3、设置rcparams

我们还可以通过修改默认rc设置的方式改变样式,所有rc设置都保存在一个叫做 matplotlib.rcParams的变量中。

修改过后再绘图,可以看到绘图样式发生了变化。

plt.style.use('default') # 恢复到默认样式plt.plot([1,2,3,4],[2,3,4,5]);

# 修改参数 设置mpl.rcParams['lines.linewidth'] = 2mpl.rcParams['lines.linestyle'] = '--'plt.plot([1,2,3,4],[2,3,4,5]);

另外matplotlib也还提供了一种更便捷的修改样式方式,可以一次性修改多个样式。

mpl.rc('lines', linewidth=4, linestyle='-.')plt.plot([1,2,3,4],[2,3,4,5]);

mpl.rc('lines', linewidth=4, linestyle='-.')mpl.rc('axes', titlesize = 24, labelsize = 30)plt.xlabel('xlabel')plt.title("This is title")plt.plot([1,2,3,4],[2,3,4,5]);

1.4、修改 matplotlibrc

由于matplotlib是使用matplotlibrc文件来控制样式的,也就是上一节提到的rc setting,所以我们还可以通过修改matplotlibrc文件的方式改变样式。

# 查找matplotlibrc文件的路径mpl.matplotlib_fname()

'E:\\Anaconda3\\envs\\pytorch\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'

2、matplotlib的色彩设置(color)

在可视化中,如何选择合适的颜色和搭配组合也是需要仔细考虑的,色彩选择要能够反映出可视化图像的主旨。

从可视化编码的角度对颜色进行分析,可以将颜色分为色相、亮度和饱和度三个视觉通道。

通常来说:

色相: 没有明显的顺序性、一般不用来表达数据量的高低,而是用来表达数据列的类别。

明度和饱和度: 在视觉上很容易区分出优先级的高低、被用作表达顺序或者表达数据量视觉通道。

具体关于色彩理论部分的知识,不属于本教程的重点,请参阅有关拓展材料学习:/p/88892542

2.1、RGB或RGBA

# 设置绘图样式plt.style.use('default')

# 颜色用[0,1]之间的浮点数表示,四个分量按顺序分别为(red, green, blue, alpha),其中alpha透明度可省略plt.plot([1,2,3],[4,5,6],color=(0.1, 0.2, 0.5))plt.plot([4,5,6],[1,2,3],color=(0.1, 0.2, 0.5, 0.5));

2.2、HEX RGB 或 RGBA

# 用十六进制颜色码表示,同样最后两位表示透明度,可省略plt.plot([1,2,3],[4,5,6],color='#0f0f0f')plt.plot([4,5,6],[1,2,3],color='#0f0f0f80');

RGB颜色和HEX颜色之间是可以一一对应的,以下网址提供了两种色彩表示方法的转换工具:/

2.3、灰度色阶

# 当只有一个位于[0,1]的值时,表示灰度色阶plt.plot([1,2,3],[4,5,6],color='0.5');

2.4、单字符基本颜色

# matplotlib有八个基本颜色,可以用单字符串来表示,#分别是'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w',对应的是blue, green, red, cyan, magenta, yellow, black, and white的英文缩写plt.plot([1,2,3],[4,5,6],color='m');

2.5、颜色名称

# matplotlib提供了颜色对照表,可供查询颜色对应的名称plt.plot([1,2,3],[4,5,6],color='tan');

2.6、使用colormap设置一组颜色

有些图表支持使用colormap的方式配置一组颜色,从而在可视化中通过色彩的变化表达更多信息。

在matplotlib中,colormap共有五种类型:

顺序(Sequential):通常使用单一色调,逐渐改变亮度和颜色渐渐增加,用于表示有顺序的信息

发散(Diverging):改变两种不同颜色的亮度和饱和度,这些颜色在中间以不饱和的颜色相遇;当绘制的信息具有关键中间值(例如地形)或数据偏离零时,应使用此值。

循环(Cyclic):改变两种不同颜色的亮度,在中间和开始/结束时以不饱和的颜色相遇。用于在端点处环绕的值,例如相角,风向或一天中的时间。

定性(Qualitative):常是杂色,用来表示没有排序或关系的信息。

杂色(Miscellaneous):一些在特定场景使用的杂色组合,如彩虹,海洋,地形等。

在以下官网页面可以查询上述五种colormap的字符串表示和颜色图的对应关系:/stable/tutorials/colors/colormaps.html

import numpy as npimport matplotlib as mplimport matplotlib.pyplot as pltfrom colorspacious import cspace_converter

cmaps = {}gradient = np.linspace(0, 1, 256)gradient = np.vstack((gradient, gradient))def plot_color_gradients(category, cmap_list):# Create figure and adjust figure height to number of colormapsnrows = len(cmap_list)figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh))fig.subplots_adjust(top=1 - 0.35 / figh, bottom=0.15 / figh,left=0.2, right=0.99)axs[0].set_title(f'{category} colormaps', fontsize=14)for ax, name in zip(axs, cmap_list):ax.imshow(gradient, aspect='auto', cmap=mpl.colormaps[name])ax.text(-0.01, 0.5, name, va='center', ha='right', fontsize=10,transform=ax.transAxes)# Turn off *all* ticks & spines, not just the ones with colormaps.for ax in axs:ax.set_axis_off()# Save colormap list for later.cmaps[category] = cmap_list

2.6.1、顺序(Sequential)

# 顺序(Sequential):通常使用单一色调,逐渐改变亮度和颜色渐渐增加,用于表示有顺序的信息plot_color_gradients('Perceptually Uniform Sequential',['viridis', 'plasma', 'inferno', 'magma', 'cividis'])

plot_color_gradients('Sequential',['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds','YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu','GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'])

plot_color_gradients('Sequential (2)',['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone','pink', 'spring', 'summer', 'autumn', 'winter', 'cool','Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'])

2.6.2、发散(Diverging)

plot_color_gradients('Diverging',['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu','RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'])

2.6.3、循环(Cyclic)

plot_color_gradients('Cyclic', ['twilight', 'twilight_shifted', 'hsv'])

2.6.4、定性(Qualitative)

plot_color_gradients('Qualitative',['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2','Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b','tab20c'])

2.6.5、杂色(Miscellaneous)

plot_color_gradients('Miscellaneous',['flag', 'prism', 'ocean', 'gist_earth', 'terrain','gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap','cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet','turbo', 'nipy_spectral', 'gist_ncar'])plt.show()

# 示例# RdPu为Sequential子类x = np.random.randn(50)y = np.random.randn(50)plt.scatter(x,y,c=x,cmap='RdPu');plt.scatter(x,y,c=x,cmap='flag');

3、思考题

学习如何自定义colormap,并将其应用到任意一个数据集中,绘制一幅图像,注意colormap的类型要和数据集的特性相匹配,并做简单解释

# 参考链接:Python数据可视化matplotlib:第五回:样式色彩秀芳华_林遠夏的博客-程序员秘密:https://url.cy/wryWK2# 三种不同的颜色,分别代表了鸢尾花三种类型的数据,这里使用的是sklearn库自带的数据,方便处理。import pandas as pd #数据分析、处理import numpy as np #科学计算包import matplotlib.pyplot as plt #画图from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_split iris_dataset = load_iris() # sklearn已经整理了Iris数据集,使用load_iris函数可以直接下载,使用;#导入数据iris = load_iris()X = iris.data[:,:2] #指选择第一个和第三个特征作为输入y = iris.target # 输出x_min,x_max = X[:,0].min()-.5, X[:,0].max()+.5y_min,y_max = X[:,1].min()-.5, X[:,1].max()+.5plt.figure(2,figsize=(8,6))plt.clf()plt.scatter(X[:,0],X[:,1],c=y,cmap=plt.cm.Set1,edgecolor='k')plt.xlabel('Sepal length')plt.ylabel('Sepal width')#以花瓣长度和宽度为横纵坐标绘制一个图plt.xlim(x_min, x_max)plt.ylim(y_min, y_max)plt.xticks(())plt.yticks(())plt.show()

使用 matplotlib 自定义Colormap

自定义 colormap 通常要使用 matplotlib.colors 模块中提供的函数和方法。

matplotlib.colors 是用来转换数字列表或颜色参数为 RGB 或 RGBA 的模块。RGB 和 RGBA 是具有3个或4个浮点数且数值在 [0, 1] 之间的序列。

创建 colormap 时通常需要以下两步:

1、使用 Normalize 实例或子类将数据数组归一化为 [0 1]之间的数组

2、使用 Colormap 子类的实例进行数据和颜色的映射

模块中提供了以下两个函数创建 colormap:

LinearSegmentedColormap :有内置 colormap 实例均由此函数创建,但也可以自定义colormap

ListedColormap :从颜色列表创建 colormap

3.1、使用 LinearSegmentedColormap 的 from_list 方法创建 colormap

参考链接:

python colormap_Python matplotlib的使用并自定义colormap的方法:/weixin_39739661/article/details/110753542

使用 matplotlib 自定义Colormap:/developer/article/1618345

# 显示原图片import matplotlib.pyplot as plt # plt 用于显示图片import matplotlib.image as mpimg # mpimg 用于读取图片import numpy as nplena = mpimg.imread('img_188.jpg') # 读取和代码处于同一目录下的 lena.png# 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理lena.shape #(512, 512, 3)plt.imshow(lena) # 显示图片plt.axis('off') # 不显示坐标轴

(-0.5, 4023.5, 3035.5, -0.5)

from matplotlib.colors import LinearSegmentedColormapimport randomimport matplotlib.image as mpimg# R, G, B 三色colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]# 用于进行 colormap 插值,表示 colormap 颜色区间n_bins = [3, 6, 10, 100] # colormap 名cmap_name = 'my_cmap'fig, axs = plt.subplots(2, 2, figsize=(6, 9))fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)data=mpimg.imread('img_188.jpg')for n_bin, ax in zip(n_bins, axs.ravel()):# 创建 colormapcm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bin)# n_bin 越小,插值得到的颜色区间越少im = ax.imshow(data, interpolation='nearest', origin='lower', cmap=cm)ax.set_title("N bins: %s" % n_bin)fig.colorbar(im, ax=ax)plt.axis('off') # 不显示坐标轴plt.show()

# 添加colormap的对象是灰度图,可以变成热量图,从而更加明显的发现一些规律,适用于一些雷达图像等from PIL import Image# 将彩色图片转换成黑白图片im=Image.open("img_188.jpg")im1 = im.convert('L')# 保存图片# im.save("image.jpg")# im1.show()plt.subplot(1,2,1) plt.imshow(im)plt.axis('off') # 不显示坐标轴plt.subplot(1,2,2) plt.imshow(im1);plt.axis('off') # 不显示坐标轴

(-0.5, 4023.5, 3035.5, -0.5)

# 从图片中读取数据,转换成colormap图import matplotlib.pyplot as pltimport matplotlib.image as mpimgimport matplotlib as mplfrom PIL import Imageimport numpy as np# 自定义colormapdef colormap():return mpl.colors.LinearSegmentedColormap.from_list('cmap',['#FFFFFF', '#98F5FF', '#00FF00', '#FFFF00','#FF0000', '#8B0000'], 256)# 读取图plt.subplot(1, 2, 1)data=mpimg.imread('img_188.jpg')plt.imshow(data);# 如果需要固定colorbar的范围,可以设置参数vmin,vmax,具体参考#/api/image_api.html# 设定每个图的colormap和colorbar所表示范围是一样的,即归一化plt.subplot(1, 2, 2)plt.imsave('colormap.jpg',data, cmap=colormap())plt.imshow(data, cmap=colormap());# 这里没有显示出来colorbar的数值分布,得到的图像是等大的

3.2、使用 ListedColormap 自定义 colormap

import numpy as npimport matplotlib.pyplot as pltimport matplotlib as mplimport matplotlib.colors as colors# 生成图片格式自定义def colormap():# 白青绿黄红cdict = ['#FFFFFF', '#9ff113', '#5fbb44', '#f5f329', '#e50b32']# 按照上面定义的colordict,将数据分成对应的部分,indexed:代表顺序return colors.ListedColormap(cdict, 'indexed')# 加载数据data=mpimg.imread('img_188.jpg')fig = plt.figure()# 加载图片设置my_cmap = colormap()# 第一个子图,按照默认配置ax = fig.add_subplot(221)ax.imshow(data)# 第二个子图,使用api自带的colormapax = fig.add_subplot(222)cmap = mpl.cm.bwr # 蓝,白,红ax.imshow(data, cmap=cmap)# 第三个子图增加一个colorbarax = fig.add_subplot(223)cmap = mpl.cm.winter # 冬季风格im = ax.imshow(data, cmap=my_cmap)plt.colorbar(im) # 增加colorbar# 第四个子图可以调整colorbarax = fig.add_subplot(224)cmap = mpl.cm.rainbow# 这里设置colormap的固定值norm = mpl.colors.Normalize(vmin=-1, vmax=1)im=ax.imshow(data,cmap=cmap)plt.colorbar(im,cmap=cmap, norm=norm,ticks=[-1,0,1])# 显示plt.show()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。