使用 plotly 在 jupyter 中使 matplotlib 堆叠条形图交互
making matplotlib stacked bar chart interactive in jupyter using plotly
第一次使用jupyter & plotly,所以很纠结
这是我的代码
# 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()
产生情节:
这在 jupyter 中显示良好。
现在,我想做的是添加悬停功能,基本上与此示例完全相同:
https://plot.ly/matplotlib/bar-charts/#stacked-bar-chart-with-labels
将鼠标悬停在每个条上会显示每包的风味分布。
即:个人标签:
总计:一个,
橙色:b,
太妃糖:c,
等等
将鼠标悬停在每个数据包的栏上时会以各自口味的颜色出现。
我已经 fiddle 大约 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'对象没有属性'grouped'
如果您已经有了坐标轴,则可以使用 ax
参数将其提供给数据框 df
的 pandas 绘图函数,
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')
第一次使用jupyter & plotly,所以很纠结
这是我的代码
# 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()
产生情节:
这在 jupyter 中显示良好。
现在,我想做的是添加悬停功能,基本上与此示例完全相同:
https://plot.ly/matplotlib/bar-charts/#stacked-bar-chart-with-labels
将鼠标悬停在每个条上会显示每包的风味分布。
即:个人标签: 总计:一个, 橙色:b, 太妃糖:c, 等等 将鼠标悬停在每个数据包的栏上时会以各自口味的颜色出现。
我已经 fiddle 大约 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'对象没有属性'grouped'
如果您已经有了坐标轴,则可以使用 ax
参数将其提供给数据框 df
的 pandas 绘图函数,
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')