【问题标题】:How to distribute the same data by grouping in Python如何在 Python 中通过分组来分配相同的数据
【发布时间】:2021-08-03 06:50:51
【问题描述】:

我有一张如下表。

根据上表,我想画出3维特征的分布。它包括三个类别,例如正常,超和低。我为此创建了以下代码。

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

labels = df.class_type
for l in labels:
   attr1 = df.X1
   attr2 = df.X2
   attr3 = df.X3
   ax.scatter(xs = attr1, ys = attr2, zs = attr3, label = "normal")
   ax.scatter(xs = attr1, ys = attr2, zs = attr3, label = "hyper")
   ax.scatter(xs = attr1, ys = attr2, zs = attr3, label = "hypo")

ax.set_title("1.Grup")
ax.set_xlabel("atr1")
ax.set_ylabel("atr2")
ax.set_zlabel("atr3")

plt.show()

但我想绘制如下图。我该怎么做?提前致谢

【问题讨论】:

  • 您可以停止循环过程并修改以下内容以获得所需的输出。 ax.scatter(xs=attr1, ys=attr2, zs=attr3, c='b', label="normal");ax.scatter(xs=attr1, ys=attr3, zs=attr4, c='r', label="hyper");ax.scatter(xs=attr1, ys=attr4, zs=attr5, c='g', label="hypo")

标签: python dataframe matplotlib jupyter-notebook scatter3d


【解决方案1】:

我找到了答案。 我做了一个例子而不是你的数据框。 首先,创建一个数据框。

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import itertools

df = pd.DataFrame({'class_att': [1, 1, 2, 2, 3, 3],
                   'X1': [100, 110, 120, 130, 140, 150],
                   'X2': [10, 20, 30, 40, 50, 60],
                   'X3': [50, 60, 70, 80, 90, 100],
                   'class_type': ['normal', 'normal', 'hyper', 'hyper', 'hypo', 'hypo']})

您可以创建一个组作为 groupby() 的函数。

groups = df.groupby('class_type')

然后画散点图就大功告成了。

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

colors = itertools.cycle(["r", "b", "g"])
for name, group in groups:
    print(group)
    ax.scatter(xs=group.X1, ys=group.X2, zs=group.X3, label=name, color=next(colors), alpha=1)

ax.legend()
plt.show()

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多