简体   繁体   English

Python 散点图 plot 用于多个组,x 轴为列,y 轴为值

[英]Python scatter plot for multiple groups with columns in x-axis and values in y-axis

I have a dataframe with 6 columns - id, jan_data, feb_data, mar_data, apr_data, group.我有一个 dataframe 有 6 列 - id、jan_data、feb_data、mar_data、apr_data、组。 For the sample data I have given 2 groups and I would like to create 2 different scatter plots - one for each group(groups can be more).对于样本数据,我给了 2 个组,我想创建 2 个不同的散点图 - 每个组一个(组可以更多)。 Label should read as "group 1", "group 2". Label 应读作“组 1”、“组 2”。

X-axis should contain the columns names jan_data, feb_data, mar_data, apr_data with label as "months" and the y-axis should have name as "value"(written vertically). X 轴应包含列名称 jan_data、feb_data、mar_data、apr_data,其中 label 为“月”,y 轴的名称应为“值”(垂直书写)。 Now scatter plot has to be plotted for each id(for the corresponding months data in x-axis).现在必须为每个 id 绘制散点 plot(对于 x 轴中的相应月份数据)。

import pandas as pd
df_plot = pd.DataFrame({'id': [101,102,103,104,105,106],
                         'jan_data': [30,0,5000,5500,8900,80],
                         'feb_data': [40,0,6000,6780,7800,90],
                         'mar_data': [50,20,7000,4300,6700,78],
                         'apr_data': [60,30,8000,1200,0,67],
                         'group': [2,2,1,1,1,2]})
    id  jan_data    feb_data    mar_data    apr_data    group
0   101 30          40          50          60          2
1   102 0           0           20          30          2
2   103 5000        6000        7000        8000        1
3   104 5500        6780        4300        1200        1
4   105 8900        7800        6700        0           1
5   106 80          90          78          67          2

Can someone please help me with this.有人可以帮我解决这个问题。 Below is sample image for one group - group 1.下面是一组的示例图像 - 第 1 组。

第 1 组的样本图

First melt your DataFrame so you have a single column for the X-values and a single column for the Y-values.首先melt您的 DataFrame,这样您就有一列 X 值和一列 Y 值。 Then use groupby to create a different plot for each group.然后使用groupby为每个组创建不同的 plot。 We can specify that the id will be used for color.我们可以指定id将用于颜色。 (Use a different cmap if you expect > 20 ids in a plot). (如果您希望绘图中有 > 20 个 ID,请使用不同的cmap )。 DataFrame.plot.scatter forces a colorbar, so instead just use plt.scatter . DataFrame.plot.scatter强制使用颜色条,因此只需使用plt.scatter

import matplotlib.pyplot as plt

data = df_plot.melt(id_vars=['id', 'group'])

for idx, gp in data.groupby('group'):
    fig, ax = plt.subplots(figsize=(4,4))
    ax.scatter(x=gp['variable'], y=gp['value'],
               c=gp['id'], cmap='tab20')
    
    ax.grid()
    ax.set_ylabel('Value', fontsize=12)
    ax.set_xlabel('Months', fontsize=12)
    ax.set_title(f'Group: {idx}', fontsize=14)
    
    plt.show()

在此处输入图像描述 在此处输入图像描述

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

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