%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mpld3
from mpld3 import plugins, utils
mpld3.enable_notebook()
class BarLabelToolTip(plugins.PluginBase):
JAVASCRIPT = """
mpld3.register_plugin("barlabeltoolTip", BarLabelToolTip);
BarLabelToolTip.prototype = Object.create(mpld3.Plugin.prototype);
BarLabelToolTip.prototype.constructor = BarLabelToolTip;
BarLabelToolTip.prototype.requiredProps = ["ids","labels"];
BarLabelToolTip.prototype.defaultProps = {
hoffset: 0,
voffset: 10,
location: 'mouse'
};
function BarLabelToolTip(fig, props){
mpld3.Plugin.call(this, fig, props);
};
BarLabelToolTip.prototype.draw = function(){
var svg = d3.select("#" + this.fig.figid);
var objs = svg.selectAll(".mpld3-path");
var loc = this.props.location;
var labels = this.props.labels
test = this.fig.canvas.append("text")
.text("hello world")
.style("font-size", 72)
.style("opacity", 0.5)
.style("text-anchor", "middle")
.attr("x", this.fig.width / 2)
.attr("y", this.fig.height / 2)
.style("visibility", "hidden");
function mousemove(d) {
if (loc === "mouse") {
var pos = d3.mouse(this.fig.canvas.node())
this.x = pos[0] + this.props.hoffset;
this.y = pos[1] - this.props.voffset;
}
test
.attr("x", this.x)
.attr("y", this.y);
};
function mouseout(d) {
test.style("visibility", "hidden")
};
this.props.ids.forEach(function(id, i) {
var obj = mpld3.get_element(id);
function mouseover(d) {
test.style("visibility", "visible")
.style("font-size", 24)
.style("opacity", 0.7)
.text(labels[i])
};
obj.elements().on("mouseover", mouseover.bind(this))
});
objs.on("mousemove", mousemove.bind(this))
.on("mouseout", mouseout.bind(this));
}
"""
def __init__(self, ids, labels=None, location="mouse"):
self.dict_ = {"type": "barlabeltoolTip",
"ids": ids,
"labels": labels,
"location": location}
def stackedBarPlot(df):
fig, ax = plt.subplots()
N = df.shape[0]
ind = np.arange(N)
width = 0.8
ids = []
labels = []
bottom = N * [0]
for i in range(df.shape[1]):
bars = plt.bar(df.index, df[df.columns[i]], bottom=bottom, width=width, color=np.random.rand(3,1))
ids.extend([utils.get_id(bar) for bar in bars])
bottom = bottom + df[df.columns[i]]
labels.extend([round(bar.get_height(),2) for bar in bars])
plugins.connect(fig, BarLabelToolTip(ids, labels))
plt.xticks(ind+width/2)
N = 10
df = pd.DataFrame(index=range(N))
df['v'] = np.random.rand(N)
df['w'] = np.random.rand(N)
df['x'] = np.random.rand(N)
df['y'] = np.random.rand(N)
df['z'] = np.random.rand(N)
stackedBarPlot(df)