微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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)

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

熊猫源代码在这里

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

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

解决方法:

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

但是,正如您在链接源的第2954行所看到的,pandas将查找(未记录的)数字参数.所以你可以通过做df [‘speed’]来实现它的工作.hist(ax = ax2,figure = fig2).熊猫来源的评论指出,这是一个“黑客,直到绘图界面更加统一”,所以我不会依赖它来做任何过于挑剔的事情.

另一种解决方案是在您准备好使用它之前不要创建新的数字.在上面的示例中,您只使用图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)

您可以将其更改为:

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)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐