首页 > 解决方案 > 如何合并熊猫中的两个地块?

问题描述

我想合并两个图,这是我的数据框: df_inc.head()

id  date    real_exe_time   mean    mean+30%    mean-30%
0   Jan           31        33.14   43.0         23.0
1   Jan           30        33.14   43.0         23.0
2   Jan           33        33.14   43.0         23.0
3   Jan           38        33.14   43.0         23.0
4   Jan           36       33.14    43.0         23.0

我的第一个情节: df_inc.plot.scatter(x = 'date', y = 'real_exe_time')

分散

然后

我的第二个情节: df_inc.plot(x='date', y=['mean','mean+30%','mean-30%'])

线条

当我尝试合并时:

fig=plt.figure()
ax = df_inc.plot(x='date', y=['mean','mean+30%','mean-30%']);
df_inc.plot.scatter(x = 'date', y = 'real_exe_time', ax=ax)

plt.show()

我得到以下信息:

失败

我怎样才能以正确的方式合并?

标签: pythonpandasmatplotlib

解决方案


您不应将平均值作为额外的列重复。df.plot()对于分类数据,将根据索引绘制 - 因此您会看到原始散点图(也根据索引绘制)挤在左角。您可以创建一个额外的聚合数据框,然后将其绘制到同一个图中:

import matplotlib.pyplot as plt
import pandas as pd

#test data generation
import numpy as np
n=30
np.random.seed(123)
df = pd.DataFrame({"date": np.random.choice(list("ABCDEF"), n), "real_exe_time": np.random.randint(1, 100, n)})
df = df.sort_values(by="date").reindex()

#aggregate data for plotting
df_agg = df.groupby("date")["real_exe_time"].agg(mean="mean").reset_index()
df_agg["mean+30%"] = df_agg["mean"] * 1.3
df_agg["mean-30%"] = df_agg["mean"] * 0.7

#plot both into the same subplot
ax = df.plot.scatter(x = 'date', y = 'real_exe_time')
df_agg.plot(x='date', y=['mean','mean+30%','mean-30%'], ax=ax)

plt.show()

样本输出: 在此处输入图像描述

您还可以考虑使用seaborn,例如,用于分类数据聚合的点图。


推荐阅读