如何修复系列图例?

我试图从熊猫数据框中创建一个交互式的图解图。

但是,我无法正确显示图例

这是一个工作示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.plotly as py

# sign into the plotly api
py.sign_in("***********", "***********")

# create some random dataframes
dates = pd.date_range('1/1/2000', periods=8)
df1 = pd.DataFrame(np.random.randn(8, 1), index=dates, columns=['A'])
df2 = pd.DataFrame(np.random.randn(8, 1), index=dates, columns=['B'])
df1.index.name = 'date'
df2.index.name = 'date'

现在我试图用plotly绘制数据框。

fig, ax = plt.subplots(1,1)

df1.plot(y='A', ax=ax)
df2.plot(y='B', ax=ax)

py.iplot_mpl(fig, filename='random')

注意没有传说

平淡无奇 - 没有传说

编辑:

根据以下建议,我添加了update字典。 虽然这确实显示了这个传说,但它却让这个情节变得混乱起来:

fig, ax = plt.subplots(1,1)

df1.plot(y='A', ax=ax)
df2.plot(y='B', ax=ax)

update = dict(
    layout=dict(
        annotations=[dict(text=' ')],  # rm erroneous 'A', 'B', ... annotations
        showlegend=True                # show legend 
    )
)
py.iplot_mpl(fig, update=update, filename='random')

在这里输入图像描述

编辑2:

layout字典中删除annotations条目会导致图表正确显示,但图例不是y列名称,而是x列名称,数据框的索引名称

fig, ax = plt.subplots(1,1)

df1.plot(y='A', ax=ax)
df2.plot(y='B', ax=ax)

update = dict(
    layout=dict(
        showlegend=True                # show legend 
    )
)
py.iplot_mpl(fig, update=update, filename='random')

结果如下图所示:

在这里输入图像描述

编辑3:

我发现了一种重写图例文本的方法,但它似乎有点klunky。 鉴于我已经指定了我想绘制的数据帧列:

df1.plot(y='A', ax=ax)

我会预期y='A'会导致'A'被用作图例标签。

看起来情况并非如此,虽然可以使用索引标签来覆盖,如下所示,但它只是感觉不对。

有没有更好的方法来实现这个结果?

update = dict(
    layout=dict(
        showlegend=True,
    ),
    data=[
        dict(name='A'),
        dict(name='B'),
    ]
)
py.iplot_mpl(fig, update=update, filename='random')

在这里输入图像描述


传奇不能很好地从matplotlib转换到情节。

幸运的是,为matplotlib绘图添加一个阴谋传说非常简单:

update = dict(
    layout=dict(
        showlegend=True  # show legend 
    )
)
py.iplot_mpl(fig, update=update)

在这里查看完整的ipython笔记本。

有关更多信息,请参阅剧情用户指南。

链接地址: http://www.djcxy.com/p/37905.html

上一篇: how to fix series legend?

下一篇: Transparent inline matplotlibs in IPython