Centering a legend title with line breaks in matplotlib -
i use following code display legend title matplotlib:
import matplotlib.pyplot plt # data all_x = [10,20,30] all_y = [[1,3], [1.5,2.9],[3,2]] # plot plt.plot(all_x, all_y) # add legend, title , axis labels plt.legend( [ 'lag ' + str(lag) lag in all_x], loc='lower right', title='hello hello hello \n world') plt.show()
as can see, "world" not centered. centered, can achieve manually adding spaces:
import matplotlib.pyplot plt # data all_x = [10,20,30] all_y = [[1,3], [1.5,2.9],[3,2]] # plot plt.plot(all_x, all_y) # add legend, title , axis labels plt.legend( [ 'lag ' + str(lag) lag in all_x], loc='lower right', title='hello hello hello \n world') plt.show()
but that's cumbersome solution.
is there more proper way achieve that?
the alignment of multiline matplotlib text controlled keyword argument multialignment
(see here example http://matplotlib.org/examples/pylab_examples/multiline.html).
therefore can center title text of legend follows:
l = plt.legend(['lag ' + str(lag) lag in all_x], loc='lower right', title='hello hello hello \n world') plt.setp(l.get_title(), multialignment='center')
Comments
Post a Comment