Python 如何使用常用代码(matplotlib、pyplot、lab work)正确导入文件?
每周我都使用pyplot绘制图形,在这样做了一年并改进了图形的外观之后,我决定每周将每个脚本中的代码尽可能多地放入外部文件中 在该文件中,有:Python 如何使用常用代码(matplotlib、pyplot、lab work)正确导入文件?,python,numpy,matplotlib,module,customization,Python,Numpy,Matplotlib,Module,Customization,每周我都使用pyplot绘制图形,在这样做了一年并改进了图形的外观之后,我决定每周将每个脚本中的代码尽可能多地放入外部文件中 在该文件中,有: # 1. custom functions (they get something and return something) def cf(self, string): if (string=="-"): ret = 0 else: r
# 1. custom functions (they get something and return something)
def cf(self, string):
if (string=="-"):
ret = 0
else:
ret = float(string.replace(",", "."))
return ret
# 2. import of numpy and matplotlib.pyplot as np and plt
import numpy as np
from numpy import log as ln
from numpy import log10 as log
import matplotlib.pyplot as plt
# 3. import of "rc" from "matplotlib" and pass settings to it (i.e. font, use of LaTeX, ...)
from matplotlib import rc
if (setting=="tex"):
rc('font',**{'family':'serif', 'serif':['Computer Modern'], 'size':18})
rc('text', usetex=True)
rc('text.latex', unicode=True)
rc('axes.formatter', use_locale=True)
if (setting=="fast"):
rc('font',**{'family':'sans-serif', 'sans-serif':['Verdana'], 'size':15})
# 4. custom functions that make something easier (for example I have a new function for numpy.loadtxt() in order to work around decimal commas instead of decimal points)
def loadtxt(self, numcols=2, name="", decimal=",", skiprows=0):
if (name==""):
name = self.script_name()+".txt"
if (decimal==","):
converters = {i:self.cf for i in range (0,numcols) }
return np.loadtxt(name, converters=converters, skiprows=skiprows)
我要问的是:如何正确且最舒适地执行此操作?到目前为止,我将整个代码作为一个模块导入,而不是使用plt.foo()
,而是使用mymodule.foo()
并在mymodule
中编写了一个处理程序,如下所示:
def semilogy(self, *args, **kwargs):
plt.semilogy(*args, **kwargs)
def plot(self, *args, **kwargs):
plt.plot(*args, **kwargs)
def loglog(self, *args, **kwargs):
plt.loglog(*args, **kwargs)
TBH觉得。。。如果不是愚蠢的话,也是次优的。每当我想从plt
获得一个新的未修改函数,并且必须在模块中写入一个新的处理程序时,这也是非常不切实际的。如果是PHP,我可能会使用一个简单的“include_once()”
,包含所有代码,我可以引用所有内容,就像我直接将其包含在脚本中一样
额外的问题:如何正确地为
np.loadtxt()
编写一个处理程序,该处理程序将传递除处理程序应设置的参数外收到的所有参数
def myloadtxt (self, *args, **kwargs, decimal):
if (decimal==","):
converters = {i:myconverterfunction() for i in range (0,number_of_columns) }
return np.loadtxt(*args, **kwargs, converters=converters)
编辑:我很乐意详细说明任何事情。我知道我对我想要的东西没有绝对准确的概念,但是任何使用matplotlib绘制过多个图形的人都应该能够感受到我需要的东西。您可能想看看Seaborn做了什么: 您只需导入它并选择一种样式,它会在幕后修改Matplotlib: 它还提供了进一步的调整 有鉴于此,您可以使用它并编写自己的样式,也可以对Matplotlib执行任何操作。一旦设置好了,从用户的角度来看,它看起来相当干净
至于奖金,我认为你的
myloadtxt
不起作用-你在*args
和**kwargs
之后有一个非关键字参数。我认为您需要检查decimal
是否在kwargs
的键中,如果是,请将其从字典中删除,执行需要执行的操作并将其添加回字典。然后只需将*args
和**kwargs
传递到loadtxt
沿模块路径或当前目录将它们放在myshortcuts.py
中,并从myshortcuts import*执行操作,导入模块时,导入*不是最佳做法。您希望在AnttiHaapala避免名称空间问题。您是否已尝试将所有代码转换为一个模块,以便只需一次导入。如果是他自己的快捷模块,则不会出现名称空间问题@hrand@AnttiHaapala说得好;-)@AnttiHaapala这将适用于我自己的函数,但这也会用于导入和所有rc设置吗?