问题描述
我试图在轮廓图上添加一个颜色条,但是颜色条不是连续的.
该图是用以下代码制作的.
将 numpy 导入为 np导入matplotlib.pyplot作为plt导入 matplotlib.cmcmap = matplotlib.cm.viridisSilhouette_start = 500轮廓数 = 20outline_factor = 1.20#计算轮廓线水平cl=contour_start*contour_factor**np.arange(contour_num)negcl = cl[::-1] * -1supercl = np.concatenate([negcl,cl])#创建图fig = plt.figure(figsize=(6,5), dpi=150)ax = fig.add_subplot(111)#绘制轮廓cp = ax.contour(datab,supercl,cmap = cmap,)cbar = plt.colorbar(cp)# cbar.set_alpha(1)# cbar.draw_all()plt.show()
我尝试添加
cbar.set_alpha(1)cbar.draw_all()
但它没有用,所以我实际上认为这与谨慎的轮廓水平有关.我不确定.
我意识到不包含数据,并且代码无法按原样工作.我没有包括,因为数据加载部分依赖于另一个不常见的库.不过,我想指出的是matplotlib文档,该文档具有类似的情节,具有相似的颜色条(最后一个示例,右边的颜色条):
I am trying to make add a colorbar to my contour plot, but the bar is not continuous.
The plot was made with the following code.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
cmap = matplotlib.cm.viridis
contour_start = 500
contour_num = 20
contour_factor = 1.20
# calculate contour levels
cl = contour_start * contour_factor ** np.arange(contour_num)
negcl = cl[::-1] * -1
supercl = np.concatenate([negcl, cl])
# create the figure
fig = plt.figure(figsize=(6,5), dpi=150)
ax = fig.add_subplot(111)
# plot the contours
cp = ax.contour(datab, supercl, cmap=cmap,)
cbar = plt.colorbar(cp)
# cbar.set_alpha(1)
# cbar.draw_all()
plt.show()
I tried to add
cbar.set_alpha(1)
cbar.draw_all()
But it didn't work, so I actually think this has to do with the discreet contour levels. I'm unsure.
I realize that the data is not included and the code will not work as it is. I didn't include as the data loading part depends on a another library which is not usual. Nevertheless I would like to point to the matplotlib docs which have a similar plot with a similar colorbar (last example, right colorbar):https://matplotlib.org/examples/pylab_examples/contour_demo.html
A solution can be to create a colorbar from a different ScalarMappable than the contour plot itself. The newly created ScalarMappable would then take the range of colors from the contour plot via a Normalize
instance.
The following code is the adapted version of the contour-demo example.
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.colors
import matplotlib.pyplot as plt
x = np.arange(-3.0, 3.0, 0.025)
X, Y = np.meshgrid(x, x)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)
fig, ax = plt.subplots()
cs = plt.contour(X, Y, Z, cmap="viridis")
norm= matplotlib.colors.Normalize(vmin=cs.cvalues.min(), vmax=cs.cvalues.max())
# a previous version of this used
#norm= matplotlib.colors.Normalize(vmin=cs.vmin, vmax=cs.vmax)
# which does not work any more
sm = plt.cm.ScalarMappable(norm=norm, cmap = cs.cmap)
sm.set_array([])
fig.colorbar(sm, ticks=cs.levels)
plt.show()
这篇关于具有轮廓级别的连续色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!