python - 计算子图调整

标签 python python-3.x matplotlib

所以我计算了一些数据,现在应该将其可视化。对于每个数据元素,我想放置一个单独的子图,以便整个图形尽可能紧凑。以下是五个元素的示例:

2x3 subplots for five data elements

这是我为任意元素计数提出的原型(prototype):

import matplotlib.pyplot as plt
import numpy as np
import math

data = ... # some list of pairs of numpy arrays, for x and y axes
size = len(data)
cols = math.floor(math.sqrt(size))
rows = math.ceil(size / cols)

f, diags = plt.subplots(rows, cols)

for (row, col), diag in np.ndenumerate(diags):
    dataIdx = row * cols + col
    if dataIdx < size:
        x = data[dataIdx][0]
        y = data[dataIdx][1]
        diag.scatter(x, y)
        diag.set_title('Regressor {}'.format(dataIdx + 1))
    else: # discard empty subplots
        f.delaxes(diag)
f.show()

简短的解释:为了紧凑性,如果可能的话,我尝试以方阵的形式调整绘图。如果没有,我会为剩余的图表添加另一行。然后我迭代图表,计算数据元素的相应位置并绘制其值。如果没有找到图表的数据元素,则意味着该图表是最后一行的余数,可以丢弃。

但是,这是我可能用 C++ 或 Java 编写的代码,问题是,Pythonic 的方式是什么?

此外,当迭代数据而不是图表时,最好的解决方案是什么?我当然可以从元素索引计算图表的行/列,就像我在初始行/列计算中所做的那样,但也许有更好的方法来做到这一点......

提前致谢!

最佳答案

我可能会创建这样的情节:

size = len(data)
cols = round(math.sqrt(size))
rows = cols
while rows * cols < size:
    rows += 1
f, ax_arr = plt.subplots(rows, cols)
ax_arr = ax_arr.reshape(-1)
for i in range(len(ax_arr)):
    if i >= size:
        ax_arr[i].axis('off')
    x = data[i][0]
    y = data[i][1]
    ax_arr[i].scatter(x,y)

关于python - 计算子图调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29355281/

相关文章:

python - matplotlib 图上的不同背景颜色区域

python - skimage 调整大小给出奇怪的输出

python - Django Rest Framework 序列化器关系 : How to get list of all child objects in parent's serializer?

Python 3-Tkinter destroy() 不适用于动态检查按钮

python-3.x - 如何在视频索引器 api 中使用 python 上传视频文件?

python - 基于辅助系列从 pandas DataFrame 中进行选择

python - 在python中打印json结果

javascript - 是否有任何库可以为 JSON 数据生成元组和重构字符串?

执行 git archive 命令时出现 Python Fabric 错误

python - 更新 matplotlib 热图的美观