本文已参与「新人创作礼」活动,一起开启掘金创作之路。
准备总结一些matplotlib使用过程中遇到的问题或者是技巧,总结到这里,方便查阅。
cmap的颜色定义和使用
直接定义一个类来获取cmap中各个颜色方便使用:
使用的话:mycolor = MyColor('Accent'); mycolor.get_color();# 每次就调用获取下一个cmap中的颜色。
class MyColor(object):
def __init__(self, cmap_name):
self.color_set = plt.get_cmap(cmap_name).colors
self.idx = 0
self.color_len = len(self.color_set)
def get_color(self):
if self.idx == self.color_len - 1:
self.idx = 0
color = self.color_set[self.idx]
self.idx += 1
return color
可视化官方提供的cmap
比如查看:['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c']
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
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 colormaps
nrows = len(cmap_list)
figh = 0.35 + 0.15 + (nrows + (nrows - 1) * 0.1) * 0.22
fig, axs = plt.subplots(nrows=nrows + 1, figsize=(6.4, figh), dpi=100)
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=plt.get_cmap(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
plot_color_gradients('Qualitative',
['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2',
'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b',
'tab20c'])
运行后:
柱状图上画误差棒
如何在柱状图上画误差棒,并且能够调整误差棒颜色大小,增加横线?
效果如图:
代码如下:
import numpy as np
import matplotlib.pyplot as plt
y= np.random.rand(5) * 10
x = np.arange(1, len(y)+1)/2
y_err = np.std(y)
fig, ax = plt.subplots(figsize=(6,5), dpi=80)
err_attr={"elinewidth":2,"ecolor":"black","capsize":6} # 这是误差棒的属性
bar1 = ax.bar(x, y, yerr=y_err, error_kw=err_attr,color = ['#FF5151','#613453', '#A32456','#D23d24','#88E0EF'], width=0.25)
ax.set_ylim(bottom=0.5) # y轴最小值从0.5开始
ax.set_ylabel("Y", color='black', fontsize=20)
ax.tick_params(axis='y', labelcolor='black', labelsize=15)
ax.set_xticks(x)
legends = ['SVM','CNN','Method1','Method2','Method3']
ax.set_xticklabels(legends, fontsize=15)
plt.tight_layout()
plt.show()