【问题标题】:Map with fine hatching using Python cartopy使用 Python cartopy 绘制带有精细阴影的地图
【发布时间】:2022-01-08 21:26:11
【问题描述】:

我尝试使用 contourf 创建一个地理地图,包括阴影区域(表示重要性)​​。

这是一个 MWE:

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

lats = np.arange(-90, 91, 10)
lons = np.arange(-180, 181, 20)
data = np.sin(np.arange(len(lats)*len(lons))).reshape(len(lats), len(lons))

proj = ccrs.Robinson()
fig, ax = plt.subplots(figsize=(6, 7), subplot_kw={'projection': proj})
im = ax.contourf(
    lons, lats, data,
    transform=ccrs.PlateCarree(),
)
ax.contourf(
    lons, lats, data > data.mean(),
    transform=ccrs.PlateCarree(),
    colors='none',
    levels=[.5, 1.5],
    hatches='///////',
)

ax.coastlines()
ax.set_global()
cbar = fig.colorbar(im, ax=ax, location='bottom')

我正在努力调整孵化的属性。这是粗略的方式,我想调整它以便能够解析更精细的结构。可以通过缩放图形大小来做到这一点:

scale = 10

fig, ax = plt.subplots(figsize=(6*scale, 7*scale), subplot_kw={'projection': proj})
ax.contourf(
    lons, lats, data,
    transform=ccrs.PlateCarree(),
)
ax.contourf(
    lons, lats, data > data.mean(),
    transform=ccrs.PlateCarree(),
    colors='none',
    levels=[.5, 1.5],
    hatches='///////',
)

ax.coastlines()
ax.set_global()
cbar = fig.colorbar(im, ax=ax, location='bottom')

但这实际上会弄乱其他所有内容(文本、线宽等),并且无论如何可能都不是最好的方法。 在这种情况下,有没有更好的方法来调整影线的属性?

【问题讨论】:

    标签: python-3.x matplotlib cartopy


    【解决方案1】:

    contourf 中的参数 hatches 应该是大小为 2 的列表,因为您有两个级别。然后,您可以通过重复图案来增加影线图案的密度,例如,density*'/'。所以总的来说这条线应该是hatches=[density*'/',density*'/']。 下面是我将密度设置为 7 时的示例:

    import numpy as np
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    
    lats = np.arange(-90, 91, 10)
    lons = np.arange(-180, 181, 20)
    data = np.sin(np.arange(len(lats)*len(lons))).reshape(len(lats), len(lons))
    
    proj = ccrs.Robinson()
    fig, ax = plt.subplots(figsize=(6, 7), subplot_kw={'projection': proj})
    im = ax.contourf(
        lons, lats, data,
        transform=ccrs.PlateCarree())
    density=7
    ax.contourf(
        lons, lats, data > data.mean(),
        transform=ccrs.PlateCarree(),
        colors='none',
        levels=[.5,1.5],
        hatches=[density*'/',density*'/'],
    )
    
    ax.coastlines()
    ax.set_global()
    cbar = fig.colorbar(im, ax=ax)
    

    输出给出:

    【讨论】:

    • 啊!我误解了hatches 的工作原理,想知道为什么多个'////' 没有改变任何东西。它只是将字符串解释为列表并在第一个“/”方式之后抛出所有内容。事实上,我有两个界限,即只有一个级别。所以它就像更改 hatches='///////' -> hatches=['///////'] 一样简单,非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多