3

我正在尝试学习如何在 python 中使用 ggplot 库。在熟悉一些示例时,我注意到要获得多个系列的时间序列图,似乎有必要 pandas.melt()将数据转换为长格式。

使用 有没有办法在 ggplot 中绘制熊猫系列? 作为一个模型,我正在玩 ggplot 中的肉类数据集。虽然数据的显示看起来还可以,但是没有图例。在我的示例中,修复链接底部图例的方法失败了。

我在某处看到了一篇文章,表明图例显示仅在内联失败(在 IPython 笔记本中)。对我来说,它也无法使用 qt(在 Mac 上)显示图例。

from ggplot import *
import pandas as pd
%matplotlib inline

原始形式的“肉”数据框。

print meat.head (2)

        date  beef  veal  pork  lamb_and_mutton  broilers  other_chicken  \
0 1944-01-01   751    85  1280               89       NaN            NaN   
1 1944-02-01   713    77  1169               72       NaN            NaN   

   turkey  
0     NaN  
1     NaN  

长格式的“肉类”数据框。

meat_lng = pd.melt(meat, id_vars=['date'])
print meat_lng.head (2)

        date variable  value
0 1944-01-01     beef    751
1 1944-02-01     beef    713

plot = ggplot(aes(x='date', y='value', color='variable'), data=meat_lng) \
     + geom_line() \
     + ggtitle("Meat Production by Decade--Missing Legend")
print plot

.. 图像:: output_6_0.png

<ggplot: (280905345)>

我有PNG格式的图表。我怎样才能在这里插入它?

我希望底部的几行能给我带来传奇。

plot = ggplot(aes(x='date', y='value', color='variable'), data=meat_lng) \
     + geom_line(size=2.0) \
     + ggtitle("Meat Production by Decade")

# Code that I hoped would fix the missing legend problem.
fig = plot.draw()
ax = fig.axes[0]
offbox = ax.artists[0]
offbox.set_bbox_to_anchor((1, 0.5), ax.transAxes)
fig.show()

::

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

<ipython-input-11-9cd7998d1503> in <module>()
      4 fig = plot.draw()
      5 ax = fig.axes[0]
----> 6 offbox = ax.artists[0]
      7 offbox.set_bbox_to_anchor((1, 0.5), ax.transAxes)
      8 fig.show()


IndexError: list index out of range
4

1 回答 1

1

您引用的示例是使用 ggplot 版本 0.5.8 完成的。他们在更高版本中更改的内容从散点图中删除了图例。在 ggplot 的 github 页面上存在一个未解决的问题,但在解决之前,如果您希望显示图例,我建议您使用旧版本。

于 2014-10-11T16:15:30.977 回答