我使用matplotlib在python中生成了一个基于子图的大图.该图总共有500多个单独的图,每个图有for0个数据点.这可以使用基于for个循环的方法绘制,该方法以下面给出的最小示例为模型

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# define main plot names and subplot names
mains = ['A','B','C','D']
subs = list(range(9))

# generate mimic data in pd dataframe
col = [letter+str(number) for letter in mains for number in subs]
col.insert(0,'Time')

df = pd.DataFrame(columns=col)

for title in df.columns:
    df[title] = [i for i in range(100)]

# although alphabet and mains are the same in this minimal example this may not always be true
alphabet = ['A', 'B', 'C', 'D']
column_names = [column for column in df.columns if column != 'Time']

# define figure size and main gridshape
fig = plt.figure(figsize=(15, 15))
outer = gridspec.GridSpec(2, 2, wspace=0.2, hspace=0.2)

for i, letter in enumerate(alphabet):
    # define inner grid size and shape
    inner = gridspec.GridSpecFromSubplotSpec(3, 3,
                    subplot_spec=outer[i], wspace=0.1, hspace=0.1)

    # select only columns with correct letter
    plot_array = [col for col in column_names if col.startswith(letter)]      
        
    # set title for each letter plot
    ax = plt.Subplot(fig, outer[i])
    ax.set_title(f'Letter {letter}')
    ax.axis('off')
    fig.add_subplot(ax)
    
    # create each subplot
    for j, col in enumerate(plot_array):
        ax = plt.Subplot(fig, inner[j])   
        
        X = df['Time']
        Y = df[col]
    
        # plot waveform
        ax.plot(X, Y)

        # hide all axis ticks
        ax.axis('off')
        
        # set y_axis limits so all plots share same y_axis  
        ax.set_ylim(df[column_names].min().min(),df[column_names].max().max())
        
        fig.add_subplot(ax)  

然而,这很慢,需要几分钟来绘制图形.是否有更有效的方法(可能没有for个循环)来实现相同的结果

推荐答案

循环的问题不是打印,而是轴限制设置为df[column_names].min().min()df[column_names].max().max().

使用6个主绘图、64个子绘图和375000个数据点进行测试,当通过搜索df个最小值和最大值来设置轴限制时,示例的绘图部分需要大约360秒才能完成.但是,通过将最小值和最大值的搜索移动到循环之外.如

# set y_lims
y_upper = df[column_names].max().max()
y_lower = df[column_names].min().min()

和改变

ax.set_ylim(df[column_names].min().min(),df[column_names].max().max())

ax.set_ylim(y_lower,y_upper)

the plotting time is reduced 到 approx 24 seconds.

Python相关问答推荐

双情节在单个图上切换-pPython

如何从. text中进行pip安装跳过无法访问的库

Python(Polars):使用之前的变量确定当前解决方案的Vector化操作

如何在telegram 机器人中发送音频?

socket.gaierror:[Errno -2]名称或服务未知|Firebase x Raspberry Pi

Docker-compose:为不同项目创建相同的容器

删除pandas rame时间序列列中未更改的值

将从Python接收的原始字节图像数据转换为C++ Qt QIcon以显示在QStandardProject中

如何将新的SQL服务器功能映射到SQL Alchemy的ORM

为什么基于条件的过滤会导致pandas中的空数据框架?

实现的差异取决于计算出的表达是直接返回还是首先存储在变量中然后返回

Google Drive API获取文件计量数据

如何使用上下文管理器创建类的实例?

通过仅导入pandas来在for循环中进行多情节

如何根据日期和时间将状态更新为已过期或活动?

海运图:调整行和列标签

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

对所有子图应用相同的轴格式

Pandas—在数据透视表中占总数的百分比

Django RawSQL注释字段