【问题标题】:plot multiple columns in a different grid in same plot in different colors在不同颜色的同一图中绘制不同网格中的多列
【发布时间】:2021-08-29 07:00:03
【问题描述】:

我有一个包含三列的数据框

data = np.array([[0,'Time',27.390000],
                [0,'Score',0.027585],
                [1,'Time',47.390000],
                [1,'Score',0.23776],
                [2,'Time',65.390000],
                [2,'Score',0.44776]])
data = pd.DataFrame(data)
data.columns = ['Rounds','Metrics','WA_All_par_1']
data["WA_All_par_1"] = pd.to_numeric(data["WA_All_par_1"])

data
        Rounds  Metrics WA_All_par_1
     0  0       Time    27.390000
     1  0       Score   0.027585
     2  1       Time    47.390000
     3  1       Score   0.237760
     4  2       Time    65.390000
     5  2       Score   0.447760

我旋转数据框“指标”列

data= data.pivot(index='Rounds', columns='Metrics', values='WA_All_par_1').reset_index().rename_axis(columns=None)
data.dropna(how='all')
data.head()


    Rounds  Score       Time
 0  0       0.027585    27.39
 1  1       0.237760    47.39
 2  2       0.447760    65.39

data.set_index('Rounds').plot(figsize=(7,6), grid=True)

我想在同一个图中分别绘制两列时间和分数

【问题讨论】:

    标签: python pandas matplotlib plotly seaborn


    【解决方案1】:

    基于this example,您可以添加第二个具有不同比例的 y 轴

    ax1 = plt.gca()
    ax1.plot(data['Rounds'], data['Score'], color='red')
    ax1.set_xlabel('Rounds')
    ax1.set_ylabel("Score")
    ax1.set_ylim([0.,0.5])
    ax2 = ax1.twinx()
    ax2.plot(data['Rounds'], data['Time'], color='blue')
    ax2.set_ylabel("Time")
    ax2.set_ylim([0, 70])
    plt.show()
    

    编辑:作为替代方案,您可以使用子图。创建子图时使用sharex=True sharey=False,以便所有子图在 x 轴上使用相同的比例,但可以在 y 轴上使用不同的比例。

    fig, axs = plt.subplots(2, sharex=True, sharey=False)
    
    axs[0].plot(data['Rounds'], data['Score'], color='red')
    axs[0].set_xlabel('Rounds')
    axs[0].set_ylabel("Score")
    axs[0].set_ylim([0.,0.5])
    
    axs[1].plot(data['Rounds'], data['Time'], color='blue')
    axs[1].set_xlabel('Rounds')
    axs[1].set_ylabel("Time")
    axs[1].set_ylim([0.,70])
    
    plt.show()
    

    【讨论】:

    • 我的数据框中有两列以上,所以我想在同一个图中有单独的网格
    • 我可能误解了你的问题吗?您是否正在为每一行寻找单独的subplots
    • 是的,我想制作子图,但是,我想在 x 轴上四舍五入
    • 如何将折线图转为直方图?
    • @Khaned 我不太确定你的意思。也许你应该问另一个(新)问题,更详细地描述你在寻找什么
    猜你喜欢
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多