繁体   English   中英

遍历 dataframe 和 plot 值(散点)中对应 x 和 y 列中的每一行

[英]iterate through each row in dataframe and plot values (scatter) in corresponding x and y columns

我有一个像这样的 dataframe 在每个 x 和 y 列表中有更多变体和值:

                   x         y
variant                       
*BCDS%q3rn  [45, 59]  [18, 14]
F^W#Bfr18   [82, 76]   [12, 3]

如何遍历每个变体(每行都有一个唯一的字符串)和 plot 散点图中的 x 和 y 值? 这将产生约 40 个图,这是我想要的,因此我可以为每个变体绘制关系。 请指教。 谢谢!

You can walk through the columns of a Pandas ' DataFrame and plot them, either with the build-in plot (using Matplotlib under the hood) or by calling Matplotlib directly:

import pandas as pd
import matplotlib.pyplot as plt
# create random test data
import numpy as np
df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=['Col 1','Col 2','Col 4','Col 5'])

fig, axs = plt.subplots(1,2)

for col in df:
    # pandas plotting
    df[col].plot(ax=axs[0])
    #matplotlib plotting
    axs[1].plot(df[col])
axs[0].set_title('pandas plotting')
axs[1].set_title('matplotlib plotting')

在此处输入图像描述

您可以将每一列转换为列表并遍历它们以得到 plot。 下面我创建了线图,但您可以轻松转换代码以创建散点图。

variants = df.index.values.tolist()
x_data = df["x"].to_numpy().tolist()
y_data = df["y"].to_numpy().tolist()

for idx in range(len(variants)):
    plt.plot(x_data[idx], y_data[idx],label= variants[idx])
plt.ylabel('Y')
plt.xlabel('X')
plt.legend()
plt.show()

对于您的示例数据,plot 如下所示: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM