python - Pandas, matplotlib and plotly - how to fix series legend? -
i'm trying create interactive plotly graph pandas dataframes.
however, can't legends displayed correctly.
here working example:
import pandas pd import numpy np import matplotlib.pyplot plt import plotly.plotly py # sign plotly api py.sign_in("***********", "***********") # create 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'
now attempt plot dataframes using 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')
notice there no legend
edit:
based on suggestions below have added update
dict. although display legend, messes plot itself:
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')
edit 2:
removing annotations
entry layout
dict results in plot being displayed correctly, legend not y
column name, rather x
column name, index name of dataframe
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')
this results in following plot:
edit 3:
i have found way override legend text seems bit klunky. given i've specified dataframe column want plot:
df1.plot(y='a', ax=ax)
i have expected y='a'
result in 'a'
being used legend label.
it seems not case, , while possible override using index label, seen below, feels wrong.
is there better way achieve result?
update = dict( layout=dict( showlegend=true, ), data=[ dict(name='a'), dict(name='b'), ] ) py.iplot_mpl(fig, update=update, filename='random')
legends don't convert matplotlib plotly.
fortunately, adding plotly legend matplotlib plot straight forward:
update = dict( layout=dict( showlegend=true # show legend ) ) py.iplot_mpl(fig, update=update)
see full working ipython notebook here.
for more information, refer plotly user guide.
Comments
Post a Comment