熊猫,matplotlib和情节 - 如何修复系列传奇?

时间:2015-04-29 03:00:45

标签: python pandas matplotlib plotly

我试图从pandas数据帧创建一个交互式的图表。

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

这是一个工作示例:

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')

请注意,没有传奇

Plotly - no legend

编辑:

根据以下建议,我添加了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')

enter image description here

编辑2:

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

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')

这导致以下情节:

enter image description here

编辑3:

我找到了一种覆盖图例文字的方法,但它看起来有点笨拙。鉴于我已经指定了我要绘制的数据框列:

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')

enter image description here

0 个答案:

没有答案