5

I'm having an issue drawing a Pandas boxplot within a subplot. Based on the two ways I'm trying, creating the boxplot either removes all the subplots that I've already created, or plots the boxplot after the subplot grid. But I can't seem to draw it within the subplot grid.

import matplotlib.pyplot as plt
import pandas
from pandas import DataFrame, Series

data = {'day' : Series([1, 1, 1, 2, 2, 2, 3, 3, 3]), 
        'val' : Series([3, 4, 5, 6, 7, 8, 9, 10, 11])}
df = pandas.DataFrame(data)

The first thing I've tried is the following:

plt.figure()

plt.subplot(2, 2, 1)
plt.plot([1, 2, 3])

plt.subplot(2, 2, 4)
df.boxplot('val', 'day')

But this simply creates the plot outside of the subplots:

Attempt A enter image description here

So, I then tried supplying the axis by hand:

plt.figure()

plt.subplot(2, 2, 1)
plt.plot([1, 2, 3])

plt.subplot(2, 2, 4)
ax = plt.gca()
df.boxplot('val', 'day', ax=ax)

But this simply destroyed the subplot grid all together, as well as the initial image:

enter image description here

Any ideas how I can get my boxplot image to appear in the bottom right grid in the subplots (the one that's empty in the first set of images)?

4

1 回答 1

6

这似乎是熊猫绘图设置中的错误,或者至少是不良行为。发生的情况是,如果您向 提供by参数boxplot,pandas 会发出自己的subplots调用,删除任何现有的子图。它显然是这样做的,因此,如果您想绘制多个值,它将为每个值创建子图(例如,一天为 Y1 的一个箱线图,一天为 Y2 的另一个箱线图,等等)。

然而,它看起来应该做但它没有做的是检查你是否只绘制一个值,在这种情况下,使用提供的ax对象(如果有的话)而不是制作自己的子图。当您只绘制一个值时,它会创建一个 1×1 的子图网格,这不是很有用。它的逻辑也有点奇怪,因为它会根据您绘制的数(第一个参数的长度)创建一个网格,但只有在您提供by参数时才会这样做。其意图似乎是允许像这样的多箱图df.boxplot(['col1', 'col2']),但这样做会阻止你相当合理的尝试去做df.boxplot('col1', 'grouper1')

我建议在 pandas bug tracker上提出问题。

与此同时,一个有点骇人听闻的解决方法是这样做:

df.pivot('val', 'day', 'val').boxplot(ax=ax)

这会重塑您的数据,以便分组依据值(天)是列。重新整形的表有很多 NAs 用于val特定值不出现的day值,但在绘图时会忽略这些 NAs,因此您可以在正确的子图位置获得正确的图。

于 2013-05-11T19:03:29.997 回答