python - 在图片上调整 python pcolor 图表
问题描述
我想在图片上放一个 pcolor 图表。您知道一种自动将颜色图匹配/调整到图片的方法吗?
示例代码:
import matplotlib.pyplot as plt
import numpy as np
# my image
im = plt.imread('salad.png')
# example pcolor chart
values = np.random.rand(6, 10)
p = plt.pcolor(values)
图片:
P色图:
我试过这个:
# Create Figure and Axes objects
fig,ax = plt.subplots(1)
# display the image on the Axes
implot = ax.imshow(image)
# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(values, alpha = 0.5, cmap='viridis')
# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)
结果我在下面有这个,这不是我想要的。颜色图不适合整个图像范围:
有没有办法自动将 pcolor 图表调整为图像大小?或图像到 pcolor 图表大小?
我的意思是这样的示例结果:
提前感谢您的任何想法。
解决方案
您需要修复图像或 pcolor 叠加层的范围(即它们将被绘制的坐标范围)。
如您所见,您的图像在 x 和 y 方向的限制为 0 到 ~190,但 pcolor 在 x 和 y 方向的限制为 10 和 6。
一种选择是定义新的 x 和 y 坐标以传递给pcolor
函数。
例如:
import matplotlib.pyplot as plt
import numpy as np
# my image
im = plt.imread('stinkbug.png')
# example pcolor chart
values = np.random.rand(6, 10)
#p = plt.pcolor(values)
# Create Figure and Axes objects
fig,ax = plt.subplots(1)
# display the image on the Axes
implot = ax.imshow(im)
# Define the x and y coordinates for the pcolor plot
x = np.linspace(0, im.shape[1], values.shape[1]+1) # add 1 because we need the define the nodal coordinates
y = np.linspace(0, im.shape[0], values.shape[0]+1)
# plot the pcolor on the Axes. Use alpha to set the transparency
p = ax.pcolor(x, y, values, alpha = 0.5, cmap='viridis')
# Add a colorbar for the pcolor field
fig.colorbar(p, ax=ax)
plt.show()
或者,您可以不理会pcolor
范围,并修改imshow
范围,但这会改变imshow
图像的纵横比:
implot = ax.imshow(im, extent=[0, values.shape[1], 0, values.shape[0]])
p = ax.pcolor(values, alpha = 0.5, cmap='viridis')
推荐阅读
- r - 无法在没有 OneDrive API 的情况下使用 Power BI 中的 R 脚本在受保护的 OneDrive 文件夹上写入 csv 文件
- c# - 检查对象访问链中的 null
- javascript - 如何逐个运行 mocha 测试模块?
- c - 将无符号字符数组返回到主函数
- google-apps-script - 如何摆脱表单插件菜单中的安装按钮?
- python - 为什么 .argmax 返回 1 而不是最大值?
- postgresql - Postgres聚合函数返回错误值,状态转换函数ok
- javascript - 查找内联脚本的容器
- c# - 如何在子类中处理 XmlWriter.Create
- admin - Magento2管理面板arning:file_put_contents():仅写入68字节中的0,可能是可用磁盘空间不足