我修改了 OPs linked code snippet中的代码
这至少对我有用。但是,我还没有找到区分单个标记的方法
import matplotlib.pyplot as plt
import numpy as np
import xml.etree.ElementTree as ET
from io import BytesIO
plt.rcParams['svg.fonttype'] = 'none'
_ , ax = plt.subplots(figsize=(14,8))
Rand_Values = []
Rand_Values.append(np.random.rand(20))
Rand_Values.append(np.random.rand(20))
x_axis = range(20)
for i in range(2):
H = ax.plot(x_axis, Rand_Values[i] , label= "data set %i" % (i+1))
ThisContainer = H[-1]
ThisContainer.set_gid('hist_%i' % i )
plt.xlabel("x-axis label")
plt.ylabel("random data")
plt.title( "Interactive chart" )
leg = ax.legend(loc='upper left', bbox_to_anchor=(0, 1), ncol=1, fancybox=True, shadow=True)
for i, t in enumerate(leg.get_texts()):
t.set_gid('leg_text_%d' % i)
# Save SVG in a fake file object.
f = BytesIO()
plt.savefig(f, format="svg")
# Create XML tree from the SVG file.
ET.register_namespace("", "http://www.w3.org/2000/svg")
tree, xmlid = ET.XMLID(f.getvalue())
# --- Add interactivity ---
# Add attributes to the text objects.
for i, t in enumerate(leg.get_texts()):
el = xmlid['leg_text_%d' % i]
el.set('cursor', 'pointer')
el.set('onclick', "toggle_hist(this)")
# Create script defining the function `toggle_hist`.
script = """
<script type="text/ecmascript">
<![CDATA[
function toggle(oid, attribute, values) {
/* Toggle the style attribute of an object between two values.
Parameters
----------
oid : str
Object identifier.
attribute : str
Name of style attribute.
values : [on state, off state]
The two values that are switched between.
*/
var obj = document.getElementById(oid);
var a = obj.style[attribute];
a = (a == values[0] || a == "") ? values[1] : values[0];
obj.style[attribute] = a;
}
function toggle_hist(obj) {
var num = obj.id.replace( /^\D+/g, '');
toggle( 'leg_text_' + num, 'opacity', [1, 0.5]);
toggle( 'hist_'+ num , 'opacity', [1,0]);
}
]]>
</script>
"""
# Add a transition effect
css = tree.getchildren()[0][0]
css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;" + \
"-moz-transition:opacity 0.4s ease-out;}"
# Insert the script and save to file.
tree.insert(0, ET.XML(script))
ET.ElementTree(tree).write("svg_lineChart.svg")