1
votes

First time using jupyter & plotly, so I'm really struggling

This is my code

# import packages
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import seaborn as sns
import plotly.plotly as py
import plotly.tools as tls

from plotly.graph_objs import *
py.sign_in("x", "y")

tls.set_credentials_file(username='x', api_key='y')
tls.get_credentials_file()

fig1 = plt.figure()

%matplotlib notebook

# load data
revels_data = pd.read_csv("directory.data.txt")
rd = revels_data

# grouped bar plot
grouped = rd.groupby(["Packet number", "Flavour"])["Contents"].sum().unstack().fillna(0)
grouped.plot(kind="bar", stacked=True, color=["#a2653e", "#a6814c", "#fd5956", "#fd8d49", "#9c6da5", "#c9ae74"])

# title and axis labels
plt.title("NUMBER OF REVELS PER PACKET", weight="bold")
plt.ylabel("Contents")
plt.xlabel("Packet")

# plot median line
median = 19
plt.axhline(median, color='grey', linestyle='dashed', linewidth=0.5)

# legend properties
plt.legend(loc=2, prop={"size":7})

# extend y axis to fit legend in
axes = plt.gca()
axes.set_ylim([0,30])

# show plot
plt.show()

which produces the plot:

enter image description here

This displays in jupyter fine.

Now, what I want to do it add hover functionality essentially exactly like this example:

https://plot.ly/matplotlib/bar-charts/#stacked-bar-chart-with-labels

where hovering the mouse over each bar shows the flavour distribution per pack.

i.e: individual tabs for: total: a, orange: b, toffee: c, etc. appear when hovering over each packet's bar in their respective flavour's colour.

I have had a fiddle for about 3 hours but I am getting no where.

Please help, thanks!

EDIT:

# import packages
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import seaborn as sns
import plotly.plotly as py
import plotly.tools as tls

from plotly.graph_objs import *
py.sign_in("x", "y")

tls.set_credentials_file(username='x', api_key='y')
tls.get_credentials_file()

%matplotlib notebook

# load data
revels_data = pd.read_csv(".txt")
rd = revels_data

fig1 = plt.figure()
ax = mpl_fig.add_subplot

# grouped bar plot
grouped = rd.groupby(["Packet number", "Flavour"])["Contents"].sum().unstack().fillna(0)
ax.grouped.plot(kind="bar", stacked=True, color=["#a2653e", "#a6814c", "#fd5956", "#fd8d49", "#9c6da5", "#c9ae74"])

# title and axis labels
plt.title("NUMBER OF REVELS PER PACKET", weight="bold")
plt.ylabel("Contents")
plt.xlabel("Packet")

# plot median line
median = 19
plt.axhline(median, color='grey', linestyle='dashed', linewidth=0.5)

# legend properties
plt.legend(loc=2, prop={"size":7})

# extend y axis to fit legend in
axes = plt.gca()
axes.set_ylim([0,30])

# show plot
plotly_fig = tls.mpl_to_plotly(fig1)
py.plot()

error: AttributeError: 'function' object has no attribute 'grouped'

1
The code you show, is the code that works fine, it seems. However in order to help you one would need to know the code that you cannot get to work. So in principle the linked example shows you what to do; you'd therefore need to implement that and update your question. You then need to be very specific about what the result is and in how far it's not what you expect. If you get an error, report about the error trace. - ImportanceOfBeingErnest
my code is completely different though. the example given has manually inputed data, manually created plot etc. I want to essentially know if its possible to use all my existing design parameters WHILST making it interactive, essentially. The process is so much different to the example i posted, I just posted it as a visual representation of what it is I am trying to achieve. - pow
Yes you can do it and the way it works is exactly like in the example you link to. At the moment one cannot answer this question as it would essentially only the example code copied. Again, if you have a problem implementing it, show a minimal reproducible example of the code that causes the problem. - ImportanceOfBeingErnest
pls help me ernest - pow
Please add some data to reproduce it, we don't have access to "directory.data.txt" - Maximilian Peters

1 Answers

1
votes

If you already have an axes, you can provide it to the pandas plot function of a dataframe df using the ax argument,

fig, ax = plt.subplots()
df.plot(... , ax=ax)

Try this code (no guarantee that it works, since I cannot text it):

# import packages
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import plotly.offline as py
import plotly.tools as tls

from plotly.graph_objs import *
#py.sign_in("x", "y")

#tls.set_credentials_file(username='x', api_key='y')
#tls.get_credentials_file()

#%matplotlib notebook

# load data
flavours=["orange", "toffee", "chocolate", "malteser", "raisin", "coffee"]
num = np.arange(0, 6*36) % 36
flavs = np.random.choice(flavours, size=len(num))
conts = np.random.randint(0,6, len(num))

rd = pd.DataFrame({"Packet number":num ,"Flavour":flavs,"Contents" : conts})

fig1 = plt.figure(figsize=(10,8))
ax = fig1.add_subplot(111)

# grouped bar plot
grouped = rd.groupby(["Packet number", "Flavour"])["Contents"].sum().unstack().fillna(0)
grouped.plot(kind="bar", stacked=True, legend=False,
             color=["#a2653e", "#a6814c", "#fd5956", "#fd8d49", "#9c6da5", "#c9ae74"], ax=ax)

#ax.plot([1,3])

# title and axis labels
plt.title("NUMBER OF REVELS PER PACKET")
plt.ylabel("Contents")
plt.xlabel("Packet")

# plot median line, not shown in plotly
median = 19
ax.axhline(median, color='grey', linestyle='dashed', linewidth=0.5)


# show plot
plotly_fig = tls.mpl_to_plotly(fig1)

# For Legend
plotly_fig["layout"]["showlegend"] = True
# change this to label the legend
#plotly_fig["data"][0]["name"] = "Men"
#plotly_fig["data"][1]["name"] = "Women"


plot_url = py.plot(plotly_fig, filename='stacked-bar-chart.html')

enter image description here