无法创建3x3的子图网格以单独显示9系列 [英] Not able to create a 3x3 grid of subplots to visualize 9 Series individually
问题描述
我想要一个 3x3 的子图网格来分别可视化每个系列.我首先创建了一些玩具数据:
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()
使用这些代码行,问题是我得到了3x3网格,但是所有列都已绘制在右下角的同一subplotsAxes上.所有行右下角
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])
但是现在我在每个子图轴上绘制了所有列.所有AxesSubplot用相同的行
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])
但是我得到:TypeError:"AxesSubplot"对象不可下标
But I get: TypeError: 'AxesSubplot' object is not subscriptable
很抱歉,但不知道该怎么办.
I am sorry but can't figure out what to do.
推荐答案
当前,您正在绘制每个子图中的每个系列:
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()
这篇关于无法创建3x3的子图网格以单独显示9系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!