Getting an object in Python Matplotlib

送分小仙女□ 提交于 2020-02-23 08:10:30

问题


To make a plot, I have written my code in the following fashion:

from pylab import *

x = [1,2,3]
y = [1,2,3]

matplotlib.pyplot.scatter(x,y,label='Blah')
matplotlib.pyplot.legend(title='Title')
matplotlib.pyplot.show()

I want to change the font size of the legend title. The way to go about this is to get the legend object and then change the title that way (e.g., How to set font size of Matplotlib axis Legend?)

Instead of rewriting all my code using ax.XXX, figure.XXX, etc, is there any way to get at the legend object from the code I have written, and then go from there?

That is to say, how do I define

Legend

from my original piece of code, such that

Title = Legend.get_title()
Title.set_fontsize(30)

would get at the title object and then allow me to play with .get_title()?

I think I'm on the verge of a eureka moment regarding object-orientated languages. I have a feeling a good answer will give me that eureka moment!

cheers,

Ged


回答1:


First, in your code you should stick to using either from pylab import * and then use the imported methods directly, or import matplotlib.pyplot as plt and then plt.* instead of matplotlib.pyplot.*. Both these are "conventions" when it comes to working with matplotlib. The latter (i.e. pyplot) is generally preferred for scripting, as pylab is mainly used for interactive plotting.

To better understand the difference between pylab and pyplot see the matplotlib FAQ.

Over to the problem at hand; to "get" an object in Python, simply assign the object to a variable.

from pylab import *

x = [1,2,3]
y = [1,2,3]

scatter(x,y,label='Blah')

# Assign the Legend object to a variable leg
leg = legend(title='Title')
leg_title = leg.get_title()
leg_title.set_fontsize(30)

# Optionally you can use the one-liner
#legend(title='Title').get_title().set_fontsize(30)

show()

Visual comparison (rightmost subplot produced with the above code):



来源:https://stackoverflow.com/questions/18102423/getting-an-object-in-python-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!