简体   繁体   English

matplotlib 子图 alignment 与散点图 plot 和颜色条

[英]matplotlib subplot alignment with scatter plot and color bar

I am trying to make a plot where a regular plot and a scatter plot share the x-axis.我正在尝试制作 plot ,其中常规 plot 和散点 plot 共享 x 轴。 This works fine as long as no color bar is created for the scatter plot.只要没有为散点图 plot 创建颜色条,此方法就可以正常工作。 However, when I add the color bar, then only the scatter plot gets rescaled end the x-axis is no longer shared correctly.但是,当我添加彩条时,只有散点图 plot 重新缩放,x 轴不再正确共享。

I want the color bar to be on the right of the scatter plot only.我希望彩条仅位于散点 plot 的右侧。

What I try to achieve is that graph a gets shortened to the width of graph b.我试图实现的是图 a 被缩短到图 b 的宽度。

Currently it looks like this:目前它看起来像这样:

在此处输入图像描述

Generated with:生成:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms

x = np.linspace(0, 10, 101)
y = np.sin(x)
z = np.cos(x)

fig_width = 150/25.4
fig_height = 100/25.4
fig = plt.figure(figsize=(fig_width, fig_height))

gs = fig.add_gridspec(2, 1, hspace=0)
a = gs.subplots(sharex='col')

a[1].set_xlabel("x")
trans = mtransforms.ScaledTranslation(10/72, -5/72, fig.dpi_scale_trans)
a[0].text(0.0, 1.0, "a", transform=a[0].transAxes + trans,
        fontsize='medium', verticalalignment='top', fontfamily='serif',
        bbox=dict(facecolor='1.0', edgecolor='none', pad=3.0))
a[1].text(0.0, 1.0, "b", transform=a[1].transAxes + trans,
        fontsize='medium', verticalalignment='top', fontfamily='serif',
        bbox=dict(facecolor='1.0', edgecolor='none', pad=3.0))
a[0].plot(x, y)
sc = a[1].scatter(x, y, c=z, s=3)
cbar = fig.colorbar(sc, ax=a[1])
cbar.set_label('text')
plt.show()

The trick is to create 4 axis with layout below.诀窍是使用下面的布局创建 4 轴。 Then we just hide unnecessary lines, ticks etc.然后我们只是隐藏不必要的线条、刻度等。

在此处输入图像描述

The code below should produce the desired output.下面的代码应生成所需的 output。

fig = plt.figure(figsize=(fig_width, fig_height))
gs = fig.add_gridspec(2, 2, hspace=0, wspace=0, width_ratios=[10, 1])
a = gs.subplots(sharex='col')

a[0, 1].axis('off')
a[1, 1].axis('off')

a[1, 0].set_xlabel("x")





trans = mtransforms.ScaledTranslation(10/72, -5/72, fig.dpi_scale_trans)

a[0, 0].text(0.0, 1.0, "a", transform=a[0, 0].transAxes + trans,
        fontsize='medium', verticalalignment='top', fontfamily='serif',
        bbox=dict(facecolor='1.0', edgecolor='none', pad=3.0))

a[1, 0].text(0.0, 1.0, "b", transform=a[1, 0].transAxes + trans,
        fontsize='medium', verticalalignment='top', fontfamily='serif',
        bbox=dict(facecolor='1.0', edgecolor='none', pad=3.0))

a[0, 0].plot(x, y)

sc = a[1, 0].scatter(x, y, c=z, s=3)

cbar = fig.colorbar(sc, ax=a[1, 1])
cbar.set_label('text')

plt.show()

在此处输入图像描述

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

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