【问题标题】:Plot data on top of image when image and data have different sizes当图像和数据具有不同大小时,在图像顶部绘制数据
【发布时间】:2021-11-15 15:59:08
【问题描述】:

有很多与将图像添加到绘图相关的问题。然而,在所有这些问题中,绘制在图像顶​​部的数据具有相同的大小。比如this question中,散点直接绘制到图片坐标中。

我需要的是别的东西。我有以下数据(示例)和我希望合并的以下图像:

fig, axes = plt.subplots(1,3, figsize=(15,6), sharey=True)
axes = axes.flatten()

for ax in axes:
    x = [1,2,3,4,5]
    y = x
    ax.bar(x,y)

fig, axes = plt.subplots(1,3, figsize=(15,6), sharey=True)
axes = axes.flatten()

for ax, im in zip(axes,images):
    ax.imshow(im, alpha=0.5)

现在,如果我尝试将条形图和图像绘制到同一个轴上,条形图将小到不可见。例如看set_xticks的效果。

for ax, im in zip(axes,images):
    x = [1,2,3,4,5]
    y = x
    ax.bar(x,y)
    ax.set_xticks([1,2,3,4,5])
    ax.imshow(im, alpha=0.5)

问题:

如何在图像上绘制数据?我用twinx 尝试过,但无法正常工作。

我尝试重新调整数据以适应图像的大小。

def scale_data(data, size):
    return [int(x/max(data)*size) for x in data]

但是imshow 函数也会翻转 y 轴。现在,我可以先翻转图像,然后自己再次翻转 y 轴,重新调整所有数据以使其适合图像,然后设置条的适当宽度,但这一切都感觉很复杂,我假设有我只是缺少一个更简单的解决方案。

实现所需行为的最佳方法是什么?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    如果要在图像顶部绘制图形,请使用范围参数进行调整。在这种情况下,调整它以匹配条形图的 x 轴。例如,我们使用来自官方reference 的图片。此外,子图不属于此作业的一部分,因此我们使用了单个图。

    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    import matplotlib.cbook as cbook
    
    with cbook.get_sample_data('grace_hopper.jpg') as image_file:
        image = plt.imread(image_file)
    
    fig, ax = plt.subplots()
    x = [1,2,3,4,5]
    y = x
    ax.bar(x, y)
    
    im = ax.imshow(image, extent=[0,5.5,0,5.5])
    
    plt.show()
    

    【讨论】:

    • 这个不错。但这仅在轴相等时才有效。如果 x 范围大于/小于 y 范围怎么办?
    猜你喜欢
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2014-09-06
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多