python - 继承自matplotlib

标签 python inheritance matplotlib

我想创建自己的绘图类,如下所示,但在使用 plt 模块时找不到从 Figure 继承的方法(见下文)。它要么继承 Figure,要么更改 tick_paramsFigure 是一个类,所以我可以继承,但 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/

相关文章:

java - 向上转型向下转型

python - 基于 pandas 数据框中的值的颜色编码表格图

python - 将全局设置应用于 pyplot 中的所有子图

python - 从每个列表中提取第 n 个元素并将其存储在新列中

python - 是否可以用python解析python并提取可执行表达式?

python - 使用python3.5的aiohttp查询get URL的参数

Python-UnboundLocalError : local variable 'obj' referenced before assignment

Swift 类继承输出说明

python - Matplotlib 和 Latex Beamer : Correct size

python - 带分页的 Django API 列表 - 页面不是 JSON 可序列化的