Not able to create a 3x3 grid of subplots to visualize 9 Series individually

本小妞迷上赌 提交于 2021-01-29 16:25:27

问题


I want to have a 3x3 grid of subplots to visualize each Series individually. I first created some toy data:

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'])

Here is the first code I wrote:

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

With these lines of code the problem is that I get the 3x3 grid but all the columns have been plotten on the same subplotsAxes, in the bottom right corner. Bottom Right Corner with all Lines

Here is the second thing I tried:

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

But now I get all the columns plotted on every single subplotAxes. All AxesSubplot with same lines

And if I try something like this:

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

But I get: TypeError: 'AxesSubplot' object is not subscriptable

I am sorry but can't figure out what to do.


回答1:


Currently you're plotting each series in each of the subplots:

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

Following your example code, here is a way to only plot a single series per subplot:

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


来源:https://stackoverflow.com/questions/59512068/not-able-to-create-a-3x3-grid-of-subplots-to-visualize-9-series-individually

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