我想创建自己的绘图类,如下所示,但在使用 plt
模块时找不到从 Figure
继承的方法(见下文)。它要么继承 Figure
,要么更改 tick_params
。 Figure
是一个类,所以我可以继承,但 plt
不是一个模块?我只是一个初学者,试图找到自己的出路......
有人可以告诉我它是如何工作的吗?
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
相关的修改,并得到了可接受的结果,如下所示:
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()
关于python - 继承自matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38098026/