我有一个包含多个类别的数据框,我想使用 groupby 单独绘制每个类别。但是,第一个类别(或第一个图)总是绘制两次。
例如:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
n = 100000
x = np.random.standard_normal(n)
y1 = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
y2 = 1.0 + 5.0 * x + 2.0 * np.random.standard_normal(n)
df1 = pd.DataFrame({"A": x,
"B": y1})
df2 = pd.DataFrame({"A": x,
"B": y2})
df1["Cat"] = "Cat1"
df2["Cat"] = "Cat2"
df = df1.append(df2, ignore_index=True)
df.groupby("Cat").plot.hexbin(x="A", y="B",cmap = "jet")
plt.show()
这将给我三个图,其中 Cat1 被绘制了两次。
我只想要两个情节。我做错了什么?
请您参考如下方法:
这是预期的行为,请参阅 docs 中的警告:
Warning: In the current implementation apply calls func twice on the first group to decide whether it can take a fast or slow code path. This can lead to unexpected behavior if func has side-effects, as they will take effect twice for the first group.
在您的例子中,绘图函数被调用了两次,这在结果中可见。
