在Python Matplotlib中获取对象 [英] Getting an object in Python Matplotlib

查看:122
本文介绍了在Python Matplotlib中获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要进行绘图,我以以下方式编写了代码:

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?)

不是使用ax.XXX,figure.XXX等重写我的所有代码,有什么方法可以从我编写的代码中获取图例对象,然后从那里去?

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)

会得到标题对象,然后让我玩.get_title()吗?

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!

欢呼

吉德

推荐答案

首先,在代码中,您应该坚持使用from pylab import *然后直接使用导入的方法,或者先使用import matplotlib.pyplot as plt然后使用plt.*代替matplotlib.pyplot.*.在使用matplotlib时,这两个都是约定".后者(即pyplot)通常首选用于脚本编写,因为pylab主要用于交互式绘图.

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.

要更好地了解pylab和pyplot之间的区别,请参见 matplotlib常见问题解答.

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

解决眼前的问题;要在Python中获取"对象,只需将对象分配给变量即可.

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):

这篇关于在Python Matplotlib中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆