python中使用循环的子图

2024-04-20 01:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在df上循环,在子图中绘制一些数据。我的数据列是一个字母,加上一个整数。你知道吗

df = {'x1': [2, 4, 7, 5, 6],
     'x2': [2, 7, 2, 6, 3],
     'y1': [4, 3, 2, 8, 7],
     'y2': [2, 2, 4, 6, 4],
     'z1': [2, 2, 2, 6, 7],
     'z2': [3, 1, 4, 5, 9]}
df = pd.DataFrame(df, index=range(0,5))

letterlist=['x', 'y', 'z']
numberlist=['1', '2']
tickers = df.columns

其中df的索引是我df中的一组日期

我试图实现两个目标: 1) A、B和C的一段代码(每个图中有2行) 2) 1和2的另一段代码(每个绘图将有3行in、X、Y和Z)

我试着循环查看字母表和数字表,因为我的df要大得多:

所以我试着:

fig = plt.figure(figsize=(8,8))

for ticker, num in zip(tickers, xrange(1,len(letterlist))):
        ax = fig.add_subplot(len(letterlist),1,num)
        ax.plot(df[ticker])
        ax.set_title(ticker)

plt.tight_layout()
plt.show()

但我不断出错,我的指数化是错误的,我想。。所以被卡住了。有什么想法吗?你知道吗

预期输出为: 图1 1x3子图,绘制了x1和x2、y1和y2以及z1和z2 图2 1x2子地块,绘制x1、y1和z1,以及x2、y2和z2

谢谢


Tags: 数据代码df绘制pltaxtickerx1
1条回答
网友
1楼 · 发布于 2024-04-20 01:49:45

实现所需输出的一种方法是:

from matplotlib import pyplot as plt
import pandas as pd
#define the dataframe
df = {'x1': [2, 4, 7, 5, 6],
     'x2': [2, 7, 2, 6, 3],
     'y1': [4, 3, 2, 8, 7],
     'y2': [2, 2, 4, 6, 4],
     'z1': [2, 2, 2, 6, 7],
     'z2': [3, 1, 4, 5, 9]}
df = pd.DataFrame(df, index=range(0,5))

letters = 3
numbers = 2
tickers = df.columns

#first figure letterwise presentation
fig, axes = plt.subplots(nrows = letters, ncols = 1, figsize=(8,8))

for i, pair in enumerate([tickers[i:i+numbers] for i in range(0, len(tickers), numbers)]):
    ax = axes[i]
    for item in pair:
        ax.plot(df[item], label = item)
    ax.legend()
    ax.set_title(", ".join(pair))
plt.tight_layout()

#second figure numberwise presentation
fig, axes = plt.subplots(nrows = numbers, ncols = 1, figsize=(8,8))

for i, pair in enumerate([tickers[i::numbers] for i in range(numbers)]):
    ax = axes[i]
    for item in pair:
        ax.plot(df[item], label = item)
    ax.legend()
    ax.set_title(", ".join(pair))
plt.tight_layout()

plt.show()

样本输出: enter image description here

但是您仍然需要手动定义您有多少个字母和数字,并且您的列必须按预期的顺序[x1,x2,x3,…,xn,y1,y2,y3,…,yn,z1…]。您可能需要研究pandas multiindex来构造一个数据帧,在这里您可以自动提取必要的信息。你知道吗

相关问题 更多 >