Python和Pandas:当Pandas将直方图绘制到特定的ax时,会出现奇怪的行为

cqc*_*991 4 python matplotlib pandas jupyter-notebook

我想将熊猫直方图绘制到轴上,但行为真的很奇怪.我不知道这里有什么问题.

fig1, ax1 = plt.subplots(figsize=(4,3))
fig2, ax2 = plt.subplots(figsize=(4,3))
fig3, ax3 = plt.subplots(figsize=(4,3))

# 1. This works
df['speed'].hist()

# 2. This doens't work
df['speed'].hist(ax=ax2)

# 3. This works
data = [1,2,3,5,6,2,3,4]
temp_df = pd.DataFrame(data)
temp_df.hist(ax=ax2)
Run Code Online (Sandbox Code Playgroud)

jupyter笔记本返回的错误是:


AssertionError                            Traceback (most recent call last)
<ipython-input-46-d629de832772> in <module>()
      7 
      8 # This doens't work
----> 9 df['speed'].hist(ax=ax2)
     10 
     11 # # This works

D:\Anaconda2\lib\site-packages\pandas\tools\plotting.pyc in hist_series(self, by, ax, grid, xlabelsize, xrot, ylabelsize, yrot, figsize, bins, **kwds)
   2953             ax = fig.gca()
   2954         elif ax.get_figure() != fig:
-> 2955             raise AssertionError('passed axis not bound to passed figure')
   2956         values = self.dropna().values
   2957 

AssertionError: passed axis not bound to passed figure
Run Code Online (Sandbox Code Playgroud)

熊猫源代码在这里:

https://github.com/pydata/pandas/blob/d38ee272f3060cb884f21f9f7d212efc5f7656a8/pandas/tools/plotting.py#L2913

完全不知道我的代码有什么问题.

Bre*_*arn 7

问题是pandas通过使用gcf()获取"当前数字"来确定哪个是活动数字.当您连续创建多个图形时,"当前图形"是最后创建的图形.但你试图绘制一个较早的,这会导致不匹配.

但是,正如您在链接源的第2954行所看到的那样,pandas将查找(未记录的)figure参数.所以你可以做到这一点df['speed'].hist(ax=ax2, figure=fig2).pandas源代码中的评论指出,这是一个"黑客直到绘图界面更加统一",所以我不会依赖它来做任何过于挑剔的事情.

另一种解决方案是在您准备好使用它之前不要创建新的数字.在上面的示例中,您只使用图2,因此无需创建其他图.当然,这是一个人为的例子,但在现实生活中,如果你有这样的代码:

fig1, ax1 = plt.subplots(figsize=(4,3))
fig2, ax2 = plt.subplots(figsize=(4,3))
fig3, ax3 = plt.subplots(figsize=(4,3))

something.hist(ax=ax1)
something.hist(ax=ax2)
something.hist(ax=ax3)
Run Code Online (Sandbox Code Playgroud)

您可以将其更改为:

fig1, ax1 = plt.subplots(figsize=(4,3))
something.hist(ax=ax1)

fig2, ax2 = plt.subplots(figsize=(4,3))
something.hist(ax=ax2)

fig3, ax3 = plt.subplots(figsize=(4,3))
something.hist(ax=ax3)
Run Code Online (Sandbox Code Playgroud)

也就是说,将每个绘图代码部分放在为该绘图创建图形的代码之后.