How to add specific axes to matplotlib subplot?

笑着哭i 提交于 2019-12-12 03:37:25

问题


I am trying to make a matrix plot with matplotlib.

The individual plots are made with a specific module windrose which subclasses PolarAxes. However there does not seem to be any projection defined in the module to be called as subplot kwargs. The standard polar projection does not work since some of the subclass arguments are missing.

I have tested several approaches without success (even with seaborn map considering this post: https://stackoverflow.com/a/25702476/3416205). Hereunder is the closest I have tried. Is there any way to do what I want without properly creating a new matplotlib projection associated with the specific WindroseAxes?

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()

回答1:


The github page from the windrose module actually provides an example of subplots: https://github.com/scls19fr/windrose/blob/master/samples/example_subplots.py.

The following works.

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()


来源:https://stackoverflow.com/questions/38571905/how-to-add-specific-axes-to-matplotlib-subplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!