通过行和列在matplotlib中迭代生成子图-仅绘制最终轴

时间:2018-11-20 12:38:21

标签: python python-3.x matplotlib

我正在编写代码以绘制数据中每个时间序列与所有其他时间序列的互相关性,并带有两个for循环分别索引行和列位置(列循环嵌套在行循环中)。

当前,仅图形的最终轴(即右下角)显示任何数据,并且循环的每次迭代似乎都在该轴上绘制。我想知道我是否对嵌套的for循环中的命令顺序犯了任何明显的错误,还是我误解了matplotlib函数(如子图)的输入参数。...

代码如下:

fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

for n in range(data_num):  #row index
    for p in range(data_num):  # column index
        x = data_df.iloc[:,n]  #get data for ROI according to row index
        print(x.head())
        x = x.values
        y = data_df.iloc[:,p]  #get data for ROI according to column index
        print(y.head())
        y = y.values
        axes[n,p] = plt.xcorr(x,y,normed=True)     #axes [row,column] = cross correlation plot of above data
        print(f'plotting at index [ {n} , {p}]')

2 个答案:

答案 0 :(得分:1)

这是pyplot和matplotlib起作用的一种(也许是不幸的)方式:您必须在各个轴上创建绘图,而不是将pyplot.xcorr调用的结果分配给轴。因此:axis[n,p].xcorr(...)。因此,该接口突然比通常的直接pyplot调用更加面向对象。

所有图都只出现在最后一个数字中,因为您正在调用

plt.xcorr(x,y,normed=True)

然后将返回值分配给axis数组元素并不重要,您不应该这样做,因为这会破坏原始的axis数组。
然后plt.xcorr会在同一图上相互绘制所有数据,因为pyplot通常作用于当前活动的轴,这是通过plt.subplots()创建的最后一个轴。


这是一个解释。这是一个示例解决方案(具有随机数据和简单的散点图):

import numpy as np
import matplotlib.pyplot as plt

data_num = 3

x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
for n in range(data_num):  #row index
    for p in range(data_num):  # column index
        # Call `scatter` or any plot function on the 
        # respective `axes` object itself
        axes[n,p].scatter(x[n,p], y[n,p])
        print(f'plotting at index [ {n} , {p}]')
plt.savefig('figure.png')

和figure.png看起来像(抱歉,没有颜色或符号变化,只有裸露的散点图):

enter image description here

答案 1 :(得分:0)

您可以使用flatten()命令,例如:

const users = [{
  name: "user1",
  gender: "m"
}, {
  name: "user2",
  gender: "f"
}, {
  name: "user3",
  gender: "f"
}, {
  name: "user4",
  gender: "m"
}, {
  name: "user5",
  gender: "m"
}];

const result = users.reduce((acc, cur) => {
  cur.gender === 'f' ? acc[0].push(cur) : acc[1].push(cur);
  return acc;
}, [ [], [] ]);
console.log(result);