python - twinx 弄乱了 pcolormesh 情节的颜色条
问题描述
尝试在图像顶部绘制一些值时遇到问题。问题是我无法真正正确放置彩条。正确地说,我的意思是我覆盖线图的图像。此线图的 y 轴应在其标签的右侧,然后再向右应为图像的颜色条。
这是显示问题的简化代码:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
image = np.random.randint(10, size=100).reshape(10, 10)
fig, ax = plt.subplots()
# ax2 = ax.twinx() # -> Calling this messes up the colorbar
# ax2.plot(image.sum(0), 'r') # what I actually want to do but not needed for the error
im = ax.pcolormesh(image)
cax = make_axes_locatable(ax).append_axes('right', size="5%", pad=0.4)
cbar = fig.colorbar(im, cax=cax)
下面你可以看到颜色条ax2 = ax.twinx()
上的效果(我对图像没有足够的声誉,所以 stackoverflow 用链接替换了它)。
我已经尝试过make_axes_locatable(ax).append_axes()
并且还结合了make_axes_locatable(ax).new_horizontal()
这个问题的答案:Positioning the colorbar。
查看文档,fig.colorbar()
我发现了这些论点ax
,cax
并与他们一起玩。他们做了很多,但不是我想要的。
我不确定我做错了什么,无法在互联网上找到,我很感谢任何建议。
解决方案
您是否尝试过使用 constrained_layout 的普通颜色条:
import matplotlib.pyplot as plt
import numpy as np
image = np.random.randint(10, size=100).reshape(10, 10)
fig, ax = plt.subplots(constrained_layout=True)
ax2 = ax.twinx()
ax2.plot(image.sum(0), 'r')
im = ax.pcolormesh(image)
cbar = fig.colorbar(im, ax=ax)
plt.show()
推荐阅读
- javascript - Angular 将 HttpClient 从 app.module 传递到另一个模块到服务
- c++ - 变量周围的堆栈已损坏c ++
- c# - 在 Asp.Net Core 的 Find 方法中使用 Include 和 Where
- prolog - 将十六进制字符串转换为整数
- html - 如何在烧瓶中记录信息?
- java - 运行时错误算术异常除以零
- c# - Xamarin.Forms Button.CornerRadius 出错
- java - 使用 Volley 在 Android 中更新 textview
- javascript - 将类型从@types 分配给本地代码?
- php - 电子邮件类正在创建一个额外的附件