从matplotlib继承 [英] Inherit from matplotlib
问题描述
我想按如下方式创建自己的绘图类,但是在使用plt
模块时(见下文),我找不到从Figure
继承的方法.它可以从Figure
继承,也可以更改tick_params
. Figure
是一个类,因此我可以继承,但plt
不是一个模块?我只是一个初学者,试图通过...找到答案.
I´d like to create my own plotting class as follows but I can not find a way to inherit from Figure
while using the plt
module (see below). Either it inherits from Figure
or it changes the tick_params
. Figure
is a class so I can inherit but plt
is not a module? I am just a beginner trying to find my way through...
有人可以告诉我它是如何工作的吗?
Can someone show me how it works?
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
class custom_plot(Figure):
def __init__(self, *args, **kwargs):
#fn = os.path.join(os.path.dirname(__file__), 'custom_plot.mplstyle')
self.fig = plt
self.fig.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off') # labels along the bottom edge are off
# here id like to use a custom style sheet:
# self.fig.style.use([fn])
figtitle = kwargs.pop('figtitle', 'no title')
Figure.__init__(self, *args, **kwargs)
self.text(0.5, 0.95, figtitle, ha='center')
# Inherits but ignores the tick_params
# fig2 = plt.figure(FigureClass=custom_plot, figtitle='my title')
# ax = fig2.add_subplot(111)
# ax.plot([1, 2, 3],'b')
# No inheritance and no plotting
fig1 = custom_plot()
fig1.fig.plot([1,2,3],'w')
plt.show()
推荐答案
好,与此同时,我自己找到了一个解决方案.首先,我创建了一个从Figure
继承的类custom_plot
,该类与plt.figure(FigureClass=custom_plot, figtitle='my title')
结合使用.我用cplot
收集了与plt
相关的修改,并获得了可接受的结果,请参见下文:
Ok, meanwhile I found one solution myself. First I created an inherited class custom_plot
from Figure
which I use in conjuncion with plt.figure(FigureClass=custom_plot, figtitle='my title')
. I collect the plt
related modification with cplot
and and get an acceptable result, see below:
import os
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
class custom_plot(Figure):
def __init__(self, *args, **kwargs):
figtitle = kwargs.pop('figtitle', 'no title')
super(custom_plot,self).__init__(*args, **kwargs)
#Figure.__init__(self, *args, **kwargs)
self.text(0.5, 0.95, figtitle, ha='center')
def cplot(self,data):
self.fig = plt
fn = os.path.join(os.path.dirname(__file__), 'custom_plot.mplstyle')
self.fig.style.use([fn])
self.fig.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off') # labels along the bottom edge are off
self.fig.plot(data)
fig1 = plt.figure(FigureClass=custom_plot, figtitle='my title')
fig1.cplot([1,2,3])
plt.show()
这篇关于从matplotlib继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!