首页 > 解决方案 > 如何将数据绘制为 2x 2 矩阵

问题描述

我有一个简短的表格,包括三列、两个文本列(第 1 列和第 2 列)和一个数字列。我想要一个矩阵/散点图(x 和 y 作为第 1 列和第 2 列)和标记的大小或标记的颜色作为第三列

我首先使用 MultiIndex 命令对第 1 列和第 2 列求和,因为在这些列中我确实有重复的值。应用此命令后,我确实有一个具有两级索引的新数据框。但是,我可以为索引的每个组合拟合一个单独的图(我使用以下链接作为帮助Pandas Plotting with Multi-Index。但是,我想要一个图,在 x 轴上,假设级别 = 0,在 y 轴级别= 1 和标记大小 = 第三列

数据表

    import pandas as pd
    data=pd.read_excel(path)
    new_frame=data.set_index(["Col 1", "Col 2"])
    new_frame.xs("High Humidity").plot(kind="bar")
    new_frame.xs("Low Humidity").plot(kind="bar")

使用我的代码,我只能对所有组合的绘图进行编码。但如前所述,我想要一个图,其中 x 轴可以说 Col 1,y 轴 Col 2 和标记大小 = col 3

对我的任何提示:)

标签: pythonpandasmatrixplot

解决方案


@扎拉基,

我想我找到了一个至少可以满足我需求的工作。我添加了两个额外的

columns, data["numerical Col 1"]=np.nan and data["numerical Col 2"]=np.nan

然后我在框架中做了一个循环并创建了 if 条件

import pandas as pd
import sys
import matplotlib.pyplot as plt
import numpy as np
data=pd.read_excel(r"C:\Users\116225\Desktop\test_table.xlsx")
data["numerical Col 1"]=np.nan
data["numerical Col 2"]=np.nan
for i in range(len(data["Col 1"])):
    if data.at[i,"Col 1"]=="Low Humidity":
        data.at[i,"numerical Col 1"]=np.random.randint(0,20)
    else:
        data.at[i,"numerical Col 1"]=np.random.randint(21,41)

    if data.at[i,"Col 2"]=="Pulsmax":
        data.at[i,"numerical Col 2"]=np.random.randint(0,20)
    else:
        data.at[i,"numerical Col 2"]=np.random.randint(21,41)

new_frame=data.copy()

x1, y1 = [20, 20], [0, 45]
x2, y2 = [-1, 45], [20, 20]
plt.plot(x1,y1,x2,y2,c="red")
plt.scatter(x=new_frame["numerical Col 1"],y=new_frame["numerical Col    2"],s=new_frame["Col 3"]*1e-3)
plt.tick_params(axis='both', left='off', top='off', right='off', bottom='off', labelleft='off', labeltop='off', labelright='off', labelbottom='off')

在屏幕截图中,您可以看到散点图,其中两条线指示边界 :) 在此处输入图像描述


推荐阅读