Python 如何在matplotlib颜色栏中创建自定义断点?
我从matplotlib自定义cmap示例页面借用了一个示例: 这将生成具有不同数量着色轮廓的相同图像,如“箱数”中指定的:Python 如何在matplotlib颜色栏中创建自定义断点?,python,python-2.7,matplotlib,colors,Python,Python 2.7,Matplotlib,Colors,我从matplotlib自定义cmap示例页面借用了一个示例: 这将生成具有不同数量着色轮廓的相同图像,如“箱数”中指定的:n_箱: 然而,我感兴趣的不仅仅是箱子的数量,还有颜色值之间的特定断点。例如,当右上方子批次中的nbins=6时,如何指定要填充的箱子范围,以便在这些自定义区域中填充阴影: n_bins_ranges = ([-10,-5],[-5,-2],[-2,-0.5],[-0.5,2.5],[2.5,7.5],[7.5,10]) 是否也可以指定断点的包容性?例如,我想在-2和
n_箱
:
然而,我感兴趣的不仅仅是箱子的数量,还有颜色值之间的特定断点。例如,当右上方子批次中的nbins=6
时,如何指定要填充的箱子范围,以便在这些自定义区域中填充阴影:
n_bins_ranges = ([-10,-5],[-5,-2],[-2,-0.5],[-0.5,2.5],[2.5,7.5],[7.5,10])
是否也可以指定断点的包容性?例如,我想在-2和0.5之间指定它是否为
-2边界规范
,如下所示:
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
n_bin = 6 # Discretizes the interpolation into bins
n_bins_ranges = [-10,-5,-2,-0.5,2.5,7.5,10]
cmap_name = 'my_list'
fig, ax = plt.subplots()
# Create the colormap
cm = matplotlib.colors.LinearSegmentedColormap.from_list(
cmap_name, colors, N=n_bin)
norm = matplotlib.colors.BoundaryNorm(n_bins_ranges, len(n_bins_ranges))
# Fewer bins will result in "coarser" colomap interpolation
im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm, norm=norm)
ax.set_title("N bins: %s" % n_bin)
fig.colorbar(im, ax=ax)
plt.show()
或者,如果需要比例间距,即颜色之间根据其值的距离
fig.colorbar(im, ax=ax, spacing="proportional")
像美国一样
如果
b[i]太棒了!感谢您传递文档链接,并建议添加(不是减法,对吗?)任意小的数字来移动等式的一侧。为了继续使colorbar数以线性间隔排列,我是否会像colorbar api中讨论的那样传递norm参数fig.colorbar(im,ax=ax,norm=norm)
?我用我认为你所说的线性间隔更新了答案。你实际上并不打算在问题中回答你的问题(因为如果你已经回答了,它就不再是一个问题了,对吗?),相反,你可以为你自己的问题提供答案。
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] # R -> G -> B
n_bin = 6 # Discretizes the interpolation into bins
n_bins_ranges = [-10,-5,-2,-0.5,2.5,7.5,10]
cmap_name = 'my_list'
fig, ax = plt.subplots()
# Create the colormap
cm = matplotlib.colors.LinearSegmentedColormap.from_list(
cmap_name, colors, N=n_bin)
norm = matplotlib.colors.BoundaryNorm(n_bins_ranges, len(n_bins_ranges))
# Fewer bins will result in "coarser" colomap interpolation
im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm, norm=norm)
ax.set_title("N bins: %s" % n_bin)
fig.colorbar(im, ax=ax)
plt.show()
fig.colorbar(im, ax=ax, spacing="proportional")