【问题标题】:How to add specific axes to matplotlib subplot?如何将特定轴添加到 matplotlib 子图?
【发布时间】:2016-11-29 00:58:43
【问题描述】:

我正在尝试使用 matplotlib 制作矩阵图。

各个图是使用特定模块windrose 制作的,该模块是PolarAxes 的子类。然而,模块中似乎没有定义任何投影被称为 subplot kwargs。标准的polar 投影不起作用,因为缺少一些子类参数。

我已经测试了几种方法,但都没有成功(即使考虑到这篇文章的 seaborn 地图:https://stackoverflow.com/a/25702476/3416205)。下面是我尝试过的最接近的。如果不正确创建与特定 WindroseAxes 关联的新 matplotlib 投影,有什么方法可以做我想做的事吗?

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from windrose import WindroseAxes

df = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/tmp.csv')
fig = plt.figure()
gs = gridspec.GridSpec(4, 2)

def wind_plot(x, y, title=None, axes=None, fig=None):
    ax = WindroseAxes.from_ax()
    ax.set_position(axes.get_position(fig))
    ax.bar(x, y, normed=True, opening=0.8, edgecolor='white', bins=[0, 2.5, 5, 7.5, 10])
    ax.set_title(title)

for (id_s, s) in enumerate(pd.unique(df.saison)):
    for (id_jn, jn) in enumerate(pd.unique(df.jn)):
        tmp = df.query('saison==@s & jn==@jn')
        _ = plt.subplot(gs[id_s, id_jn], polar=True)
        wind_plot(tmp.wd, tmp.ws, title=s + ' - ' + jn, axes=_, fig=fig)

plt.show()

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    windrose 模块的 github 页面实际上提供了子图的示例:https://github.com/scls19fr/windrose/blob/master/samples/example_subplots.py

    以下工作。

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    from windrose import WindroseAxes
    
    df = pd.read_csv('https://raw.githubusercontent.com/AntoineGautier/Data/master/tmp.csv')
    
    fig = plt.figure(figsize=(20, 10))
    gs = gridspec.GridSpec(2, 4)
    gp = gs.get_grid_positions(fig)  # [bottom, top, left, right]
    
    def wind_plot(x, y, title, fig, rect):
        ax = WindroseAxes(fig, rect)
        fig.add_axes(ax)
        ax.bar(x, y, normed=True, opening=0.8, edgecolor='white', bins=[0, 2.5, 5, 7.5, 10])
        ax.set_title(title, position=(0.5, 1.1))
    
    for (id_s, s) in enumerate(pd.unique(df.saison)):
        for (id_jn, jn) in enumerate(pd.unique(df.jn)):
            tmp = df.query('saison==@s & jn==@jn')
            rect = [gp[2][id_s], gp[0][id_jn],
                    gp[3][id_s]-gp[2][id_s],
                    gp[1][id_jn]-gp[0][id_jn]]  # [left, bottom, width, height]
            wind_plot(tmp.wd, tmp.ws, s + ' | ' + jn, fig, rect)
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2016-04-28
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多