Python 中单个图上的水平和垂直颜色条

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

我使用seaborn生成了KDE图,在其上覆盖了一些具有一定大小的分散点。我需要有两个颜色条来表示 KDE 的数据和分散值的大小(如下所示)。

我尝试使用 Stackoverflow here 提供的答案,但是,它没有生成所需的结果,如下面的屏幕截图所示

enter image description here

问题: 如何纠正水平颜色条,以便颜色条和主图之间存在一些垂直间隙?另外,水平条的长度有点太多,需要与主图的宽度相同。

MWE

import matplotlib.pyplot as plt
from mpl_toolkits import axes_grid1
import seaborn as sns
import numpy as np

def add_colorbar(im, aspect=20, pad_fraction=0.5, orientation='vertical', **kwargs):
    """Add a color bar to an image plot with an option for horizontal or vertical colorbars."""
    divider = axes_grid1.make_axes_locatable(im.axes)
    
    if orientation == 'horizontal':
        width = axes_grid1.axes_size.AxesX(im.axes, aspect=1./aspect)  # Horizontal colorbar
        pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
        cax = divider.append_axes("bottom", size=width, pad=pad)  # Place at the bottom
    else:
        width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)  # Default vertical colorbar
        pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
        cax = divider.append_axes("right", size=width, pad=pad)  # Place at the right
    
    return im.axes.figure.colorbar(im, cax=cax, orientation=orientation, **kwargs)

# Dummy data 
x_values = np.random.rand(100)
y_values = np.random.rand(100)
size_values = np.random.rand(100)
kd = np.random.rand(100, 2)
kde_params_x = np.mean(kd[:, 0])
kde_params_y = np.mean(kd[:, 1])

# Create a plot
fig, ax = plt.subplots(figsize=(8, 8))

# Plot the multidimensional KDE for the winning data
kde = sns.kdeplot(x=kd[:, 0], y=kd[:, 1], fill=True, cmap='crest', bw_adjust=0.5, alpha=0.7, ax=ax)

# colorbar for the KDE plot
add_colorbar(kde.collections[0], orientation='horizontal')  # orientation to 'horizontal'

# Overlay the empirical scatter plot with contrasting colors
scatter = ax.scatter(x_values, y_values, s=2,   c=size_values, cmap='plasma', alpha=0.8, edgecolor='black', linewidth=0.5, label='Empirical Data')

# Add a colorbar for the scatter plot (vertical, as before)
add_colorbar(scatter, orientation='vertical')  # vertical orientation

plt.show()
python matplotlib seaborn colorbar
1个回答
0
投票

如果您将 add_colorbar 函数替换为:

plt.colorbar(kde.collections[0], shrink=0.8, orientation='horizontal', location='bottom', pad=0.05, anchor=(0.0, 0.5))
plt.colorbar(scatter, shrink=1.0, orientation='vertical', location='right', pad=0.05, anchor=(0.0, 0.5))

您将得到:

res

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