【问题标题】:Convert multi-variable discrete list of lists into a scattered plot将列表的多变量离散列表转换为散点图
【发布时间】:2020-09-11 11:56:43
【问题描述】:

我有一个多值函数形式的列表

*[[var1, [a1,b1,...,z1], [var2, [a2,b2,...,z2]],,,[varn, [an,bn,,,,zn]]]*. 

我想先把这个转换成多值列表,形式为

*[[var1,a1], [var1,b1],,,[var1,z1],[var2,a2],[var2,b2],,,[var2,z2],,,,]* 

然后我可以将它们绘制为散点图并对其进行进一步分析。有更简单的方法吗?如果没有,你如何进行这样的转换?

如果我正在处理列表的单值列表,这是我学到的(来自我的这篇文章 How to make a binned version of a barplot?):

import numpy as np
import matplotlib.pyplot as plt

A = [[var1,val1], [var2,val2], ...[varn,valn]]  # Some single value list of lists
A = np.array(A)

numbins = 7
xmin = 8
xmax = xmin + numbins * 0.6
xrange = xmax - xmin
bounds = np.linspace(xmin, xmax, numbins + 1, endpoint=True)
mids = (bounds[:-1] + bounds[1:]) / 2
bins = [[] for _ in range(numbins)]
for x, y in A:
    bins[int((x - xmin) / xrange * numbins)].append(y)
bins = [np.array(b) for b in bins]
means = np.array([np.mean(bin) if len(bin) > 0 else np.nan for bin in bins])
stds = np.array([np.std(bin) if len(bin) > 0 else np.nan for bin in bins])

plt.stem(mids, means + stds, linefmt='k-', markerfmt='k_', use_line_collection=True)
plt.bar(mids, means, width=xrange / numbins, color='salmon', ec='k', zorder=2)
plt.scatter(A[:, 0]+np.random.uniform(-.02, .02, A.shape[0]), A[:, 1],
            s=2, color='b', alpha=0.5, zorder=3)
plt.xticks(bounds, [f'{b:.1f}' for b in bounds])
plt.yscale('log')
plt.show()

谢谢,

【问题讨论】:

    标签: arrays python-3.x list numpy multidimensional-array


    【解决方案1】:

    试试:

    [[x[0], x[1][i]] for x in A for i in range(len(x[1]))]
    

    【讨论】:

    • 虽然此代码可以解决 OP 的问题,但最好包含关于您的代码如何解决 OP 问题的说明。通过这种方式,未来的访问者可以从您的帖子中学习,并将其应用到他们自己的代码中。 SO 不是编码服务,而是知识资源。此外,高质量、完整的答案更有可能获得支持。这些功能,以及所有帖子都是独立的要求,是 SO 作为一个平台的一些优势,使其与论坛区分开来。您可以编辑以添加其他信息和/或使用源文档补充您的解释。
    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2016-03-29
    • 2011-08-21
    • 2012-03-27
    • 1970-01-01
    • 2016-09-04
    相关资源
    最近更新 更多