Inherit from matplotlib

空扰寡人 提交于 2019-12-24 06:35:06

问题


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

回答1:


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 pltrelated 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()


来源:https://stackoverflow.com/questions/38098026/inherit-from-matplotlib

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