【问题标题】:Funtion to automate plotting. Various subplots and various figures自动绘图的功能。各种子图和各种数字
【发布时间】:2019-12-29 23:12:41
【问题描述】:

我想创建一个函数,它返回各种图形,每个图形内有多达 9 个子图。也就是说,如果我想要 18 个子图,我希望有两个数字,每个数字有 9 个子图。 如果我想要 16 个子图,我想要一个图有 9 个子图,另一个图只有 7 个子图在 3x3 网格中。 首先是一些玩具数据:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

rs = np.random.RandomState(444)
dates = pd.date_range(start="2009-01-01", end='2019-12-31', freq='1D')
values = rs.randn(4017,6).cumsum(axis=0)
data = pd.DataFrame(abs(values), dates, columns =['a','b','c','d','e','f'])

现在我正在使用的代码:

fig, axes = plt.subplots(3,3, figsize=(15,6))
for (year, mini_df), ax in zip(data.groupby(data.index.year), axes.flatten()):
    mini_df['b'].plot(linewidth=1.5, ax=ax, ylim=(0,100))
    ax.set_title(year)
    ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1,3,6,9,12]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

这让我明白了:here

如您所见,仍有 2018 年和 2019 年没有出现。我可以再添加一行,但我真的很想看看你们是如何解决这个问题的。我想不出我的解决方法。提前致谢。

【问题讨论】:

  • 显然你总是想要一整年。首先,我会从你的日期计算 # 年。这给了你#的情节。然后使用 integerdivision // 和 modulo % 分别获得完整 3x3 面板的数量和最后一个部分面板的余数。

标签: python matplotlib subplot


【解决方案1】:

相当直接的方法,但它有效。

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

rs = np.random.RandomState(444)
dates = pd.date_range(start="2009-01-01", end='2019-12-31', freq='1D')
values = rs.randn(4017,6).cumsum(axis=0)
data = pd.DataFrame(abs(values), dates, columns =['a','b','c','d','e','f'])
df_group = data.groupby(data.index.year)
count = 0
col = 0
row = 0
fig, axes = plt.subplots(3,3, figsize=(15,6))

for year, index in df_group.groups.items():
    ax = axes[row, col]
    ax.set_title(year)
    ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=[1,3,6,9,12]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
    df_group.get_group(year).plot(linewidth=1.5, ax=ax, ylim=(0,100))        

    count += 1
    col += 1

    if count % 3 == 0:
        row += 1
        col = 0

    if count % 9 == 0:
        col = 0
        row = 0
        fig, axes = plt.subplots(3,3, figsize=(15,6))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多