matplotlib/seaborn 带有颜色映射的小提琴图

3
我想创建一个小提琴图,使用matplotlib或seaborn,图表根据色彩映射进行着色。
这是我得到的结果: enter image description here 这是我想要的结果(我在Photoshop中制作了此图): enter image description here 如何获得所需的图表?

调色板只是为了美观,还是映射很重要?您希望颜色按y轴值进行缩放,还是其他什么? - Diziet Asahi
映射很重要,我用它来将小提琴图与其他一些图进行比较。 - Nisba
但在这种情况下,您需要告诉人们您想要将哪个数量映射到颜色。 - ImportanceOfBeingErnest
颜色的含义由颜色映射进行解释,但更重要的是其他图表中使用的颜色如何分布(这就是为什么我使用小提琴图的原因)。 - Nisba
1
我不确定我是否理解了这个问题,但我能说的是,您需要创建一个带有所需映射的 imshow 并使用小提琴轮廓作为图像的 clip_path - ImportanceOfBeingErnest
1个回答

5

我认为应该有更好的方法来做这件事,但基于@ImportanceOfBeingErnest的评论,我想这实际上是正确的方法:

from matplotlib.path import Path
from matplotlib.patches import PathPatch
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable


x = [np.random.normal(loc=i, scale=1, size=(100,)) for i in range(5)]

fig, ax = plt.subplots()
violins = ax.violinplot(x)

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()

# create a numpy image to use as a gradient
Nx,Ny=1,1000
imgArr = np.tile(np.linspace(0,1,Ny), (Nx,1)).T
cmap = 'hsv'

for violin in violins['bodies']:
    path = Path(violin.get_paths()[0].vertices)
    patch = PathPatch(path, facecolor='none', edgecolor='none')
    ax.add_patch(patch)
    img = ax.imshow(imgArr, origin="lower", extent=[xmin,xmax,ymin,ymax], aspect="auto",
                    cmap=cmap,
                    clip_path=patch)

# colorbar
ax_divider = make_axes_locatable(ax)
cax = ax_divider.append_axes("right", size="5%", pad="2%")
norm = matplotlib.colors.Normalize(vmin=ymin, vmax=ymax)
cb = matplotlib.colorbar.ColorbarBase(cax, cmap=matplotlib.cm.get_cmap(cmap),
                                norm=norm,
                                orientation='vertical')

enter image description here


我该如何在绘图的侧边添加一个显示颜色渐变的垂直条形图?我尝试添加一个矩形,但它不起作用,我认为我必须有一个补丁,它是矩形的“反向”。 - Nisba
1
当然,您可以使用ColorbarBase和适当的规范化来创建一个色条。我已经修改了我的答案。 - Diziet Asahi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接