带有matplotlib的绘图上的颜色条件数据引发了一个循环

2024-10-05 10:07:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个下面的数据帧

import pandas as pd
import matplotlib.pyplot as plt

datas = [['RAC1','CD0287',1.52,9.88], ['RAC1','CD0695',2.08,10.05],['RAC1','CD0845',2.01,10.2], ['RAC3','CD0258',1.91,9.8], ['RAC3','CD471',1.66,9.6], ['RAC8','CD0558',1.32,9.3], ['RAC8','CD0968',2.89,10.01]]
labels = ['Plate', 'Sample', 'LogRatio', 'Strength']
df = pd.DataFrame(data = datas, columns=labels, index=[8, 3, 5, 4, 12, 44, 2])
print(df)

    Plate  Sample  LogRatio  Strength
8   RAC1  CD0287      1.52      9.88
3   RAC1  CD0695      2.08     10.05
5   RAC1  CD0845      2.01     10.20
4   RAC3  CD0258      1.91      9.80
12  RAC3   CD471      1.66      9.60
44  RAC8  CD0558      1.32      9.30
2   RAC8  CD0968      2.89     10.01

如你所见,我的数据分布在不同的板块上。 我想创建尽可能多的情节,因为我有不同的板块:3个地块。在每一块地上,我想把一块板涂成红色,另一块涂成黑色。在

到目前为止,我发现的唯一方法是手动编写每个板的代码,并将红色板更改为earch run(实际上我有30多个板,因此需要太多时间)。如果我的代码能帮助你理解:

^{pr2}$

enter image description here 这里我有我的第一个绘图板是红色的,RAC3和RAC8是黑色的,现在我希望有第二个图,RAC3是红色的(RAC1和RAC8是黑色的),第三个绘图是红色的RAC8(RAC1和RAC3是黑色的)。为此,我在我的函数中手动更改颜色,但我希望有一个解决方案来自动进行。我知道我的方式真的很糟糕,很难看,我只是不知道该怎么做。在


Tags: importaspd黑色红色datasrac3cd0287
1条回答
网友
1楼 · 发布于 2024-10-05 10:07:34

您可以在这里使用^{}和pandas Index对象的^{}循环遍历您的板块,并获得当前板块和其他板块的指数:

for label, plate_df in df.groupby("Plate"):
    plate_indices = plate_df.index
    rest_indices = df.index.difference(plate_indices)

    # do your plotting here accordingly

    print(label, plate_indices, rest_indices)

RAC1 Int64Index([8, 3, 5], dtype='int64') Int64Index([2, 4, 12, 44], dtype='int64')
RAC3 Int64Index([4, 12], dtype='int64') Int64Index([2, 3, 5, 8, 44], dtype='int64')
RAC8 Int64Index([44, 2], dtype='int64') Int64Index([3, 4, 5, 8, 12], dtype='int64')

编辑

要包含打印,只需包含matplotlib语句:

^{pr2}$

enter image description hereenter image description hereenter image description here

相关问题 更多 >

    热门问题