简体   繁体   English

具有轮廓级别的连续色条

[英]Continuous colorbar with contour levels

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 不过,我想指出的是matplotlib文档,该文档具有类似的情节,并且具有相似的颜色条(最后一个示例,右边的颜色条): 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. 一种解决方案是使用与轮廓图本身不同的ScalarMappable创建颜色条。 The newly created ScalarMappable would then take the range of colors from the contour plot via a Normalize instance. 然后,新创建的ScalarMappable将通过Normalize实例从等高线图中获取颜色范围。

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()

在此处输入图片说明

我遇到了完全相同的问题,只需在代码中的颜色条之后定义轮廓即可解决问题,仅此而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM