如何添加正负对数刻度颜色条

问题描述 投票:0回答:1

我正在尝试使用 matplotlib 在 Python 中创建 2D 热图,但在处理正值和负值时遇到困难。我的数据集包含范围从非常高到非常低的正值和负值,这非常适合用对数刻度表示,但负值将是一个问题。所以我的想法是用不同的色阶来表示它们。

具体来说,我想创建两个颜色条,一个使用对数刻度表示正值,另一个使用对数刻度表示负值的绝对值。正值应以红色图案表示,而负值应以蓝色图案表示。

这是我到目前为止的代码的简化版本:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# Generate some sample data
data = np.random.randn(10, 10)
datap = np.where(data>0, data, 0)
datan = np.abs(np.where(data<0, data, 0))

# Colorbar limits
vmin = np.abs(data).min()
vmax = np.abs(data).max()

# Create the figure and axis objects
fig, ax1 = plt.subplots()

# Create the heatmap with positive values
heatmap1 = ax1.imshow(datap, cmap='Reds', norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax))

# Create the second axis object for the negative values
ax2 = ax1.twinx()

# Create the heatmap for the negative values
heatmap2 = ax2.imshow(datan, cmap='Blues', norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax))

# Add colorbars for both heatmaps
cbar1 = fig.colorbar(heatmap1, ax=ax1, pad=0.3, label='Positive Values')
cbar2 = fig.colorbar(heatmap2, ax=ax2, pad=0.1, label='Absolute Values of Negative Values')

# Show the plot
plt.show()

但问题是我不明白如何分离颜色条,正如您在下面的结果中看到的:

我不确定如何正确添加第二个颜色条,或者可能是显示此数据集的更好方法。

你能帮我吗?

python matplotlib heatmap colorbar
1个回答
2
投票

您可以将红色条移动到蓝色条的右侧。只需更改红条的位置即可。请注意,您还必须调整图的边距,以便两个颜色条都可以出现在图中。这是一个例子:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# Generate some sample data
data = np.random.randn(10, 10)
datap = np.where(data>0, data, 0)
datan = np.abs(np.where(data<0, data, 0))

# Colorbar limits
vmin = np.abs(data).min()
vmax = np.abs(data).max()

# Create the figure and axis objects
fig, ax1 = plt.subplots()

# Create the heatmap with positive values
heatmap1 = ax1.imshow(datap, cmap='Reds', norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax))

# Create the second axis object for the negative values
ax2 = ax1.twinx()

# Create the heatmap for the negative values
heatmap2 = ax2.imshow(datan, cmap='Blues', norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax))

# Change red color bar position
cbaxes1 = fig.add_axes([0.85, 0.1, 0.03, 0.7]) 

# Add colorbars for both heatmaps
cbar1 = fig.colorbar(heatmap1, ax=ax1, pad=0.3, label='Positive Values', cax = cbaxes1)
cbar2 = fig.colorbar(heatmap2, ax=ax2, pad=0.1, label='Absolute Values of Negative Values')

# Adjust the plot margin
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.8, top=0.8)
# Show the plot
plt.show()

© www.soinside.com 2019 - 2024. All rights reserved.