【问题标题】:Not able to create a 3x3 grid of subplots to visualize 9 Series individually无法创建 3x3 的子图网格来单独可视化 9 系列
【发布时间】:2020-04-18 02:12:35
【问题描述】:

我想要一个 3x3 的子图网格来单独可视化每个系列。 我首先创建了一些玩具数据:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style='whitegrid', rc={"figure.figsize":(14,6)})

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

这是我写的第一个代码:

fig, ax = plt.subplots(3, 3, sharex=True, sharey=True)
for col in n_cols:
    ax = data[col].plot()

使用这些代码行,问题是我得到了 3x3 网格,但所有列都绘制在右下角的相同 subplotsAxes 上。 Bottom Right Corner with all Lines

这是我尝试的第二件事:

n_cols = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j']
fig, ax = plt.subplots(3, 3, sharex=True, sharey=True)
for col in n_cols:
    for i in range(3):
        for j in range(3):
            ax[i,j].plot(data[col])

但是现在我在每个 subplotAxes 上绘制了所有列。 All AxesSubplot with same lines

如果我尝试这样的事情:

fig, ax = plt.subplots(sharex=True, sharey=True)
for col in n_cols:
    for i in range(3):
        for j in range(3):
            ax[i,j].add_subplot(data[col])

但我得到: TypeError: 'AxesSubplot' 对象不可下标

我很抱歉,但不知道该怎么办。

【问题讨论】:

    标签: matplotlib subplot


    【解决方案1】:

    目前您正在绘制每个子图中的每个系列:

    for col in n_cols:
        for i in range(3):
            for j in range(3):
                ax[i,j].plot(data[col])
    

    按照您的示例代码,这是一种只为每个子图绘制一个系列的方法:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    rs = np.random.RandomState(444)
    dates = pd.date_range(start="2009-01-01", end='2019-12-31', freq='1D')
    values = rs.randn(4017,12).cumsum(axis=0)
    data = pd.DataFrame(values, dates, columns =['a','b','c','d','e','f','h','i','j','k','l','m'])
    
    n_cols = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j']
    fig, ax = plt.subplots(3, 3, sharex=True, sharey=True)
    
    for i in range(3):
        for j in range(3):
            col_name = n_cols[i*3+j]
            ax[i,j].plot(data[col_name])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2016-11-24
      • 2017-11-27
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      相关资源
      最近更新 更多