Reputation: 17720
Similarly as in this question change text style inline in matplotlib I want to write two labels in different styles (bold and normal, e.g. "bold normal") as if they were the same label without using latex.
Here something that it is working:
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
def print_label(fig):
l = fig.text(0.5, 0.5, "bold", fontweight='bold')
def on_draw(event):
xmax = l.get_window_extent().inverse_transformed(fig.transFigure).max[0]
print xmax
fig.text(xmax, 0.5, "Normal")
return False
fig.canvas.mpl_connect('draw_event', on_draw)
print_label(fig)
fig.canvas.draw()
plt.show()
but I am not happy since the usage of print_label
is not transparent: the user has to call fig.canvas.draw()
. So I tried this:
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
def print_label(fig):
l = fig.text(0.5, 0.5, "bold", fontweight='bold')
def on_draw(event):
xmax = l.get_window_extent().inverse_transformed(fig.transFigure).max[0]
print xmax
fig.text(xmax, 0.5, "Normal")
fig.canvas.mpl_disconnect(event)
fig.canvas.draw()
return False
fig.canvas.mpl_connect('draw_event', on_draw)
print_label(fig)
plt.show()
the problem there is that I am not able to disconnect the event, and I am getting:
RuntimeError: maximum recursion depth exceeded while calling a Python object
Upvotes: 2
Views: 436
Reputation: 2931
I followed the first section of: http://matplotlib.org/users/event_handling.html
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
def print_label(fig):
l = fig.text(0.5, 0.5, "bold", fontweight='bold')
def on_draw(event):
xmax = l.get_window_extent().inverse_transformed(fig.transFigure).max[0]
print xmax
fig.text(xmax, 0.5, "Normal")
fig.canvas.mpl_disconnect(cid)
return False
cid = fig.canvas.mpl_connect('draw_event', on_draw)
fig.canvas.draw()
print_label(fig)
plt.show()
Upvotes: 2