使用plotly

时间:2017-04-29 12:24:54

标签: matplotlib plotly jupyter interactive

第一次使用jupyter&情节,所以我真的很挣扎

这是我的代码

# 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()

产生情节:

enter image description here

这显示在jupyter中。

现在,我想要做的就是添加悬停功能,基本上就像这个例子一样:

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

将鼠标悬停在每个条上会显示每包的风味分布。

即:个别标签: 总计:a, 橙色:b, 太妃糖:c, 等等 将鼠标悬停在各自风味颜色的每个数据包条上时显示。

我有一个小提琴约3个小时,但我没有在哪里。

请帮助,谢谢!

编辑:

# 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()

错误:AttributeError:' function'对象没有属性'已分组'

1 个答案:

答案 0 :(得分:1)

如果您已有轴,可以使用df参数将其提供给数据框ax的pandas plot函数,

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

试试这段代码(不保证它有效,因为我无法发短信):

# 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