小编Den*_*eev的帖子

如何更改matplotlib现有轴的子图投影?

我正在尝试构造一个简单的函数,它接受一个subplot instance(matplotlib.axes._subplots.AxesSubplot)并将其投影转换为另一个投影,例如,转换为其中一个cartopy.crs.CRS投影.

这个想法看起来像这样

import cartopy.crs as ccrs
import matplotlib.pyplot as plt

def make_ax_map(ax, projection=ccrs.PlateCarree()):
    # set ax projection to the specified projection
    ...
    # other fancy formatting
    ax2.coastlines()
    ...

# Create a grid of plots
fig, (ax1, ax2) = plt.subplots(ncols=2)
# the first subplot remains unchanged
ax1.plot(np.random.rand(10))
# the second one gets another projection
make_ax_map(ax2)
Run Code Online (Sandbox Code Playgroud)

当然,我可以使用fig.add_subplot()功能:

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax1.plot(np.random.rand(10))

ax2 = fig.add_subplot(122,projection=ccrs.PlateCarree())
ax2.coastlines()
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有一个适当的matplotlib方法来改变定义的子图轴投影.不幸的是,阅读matplotlib API没有帮助.

python matplotlib subplot cartopy

29
推荐指数
2
解决办法
1万
查看次数

Pythonic方法将方法结果存储为属性

我有一个python类,其属性可以对大型数组执行操作.在第一次计算方法结果后存储方法结果的最佳方法是什么,而不是每次访问属性时都不重做操作?

例如:

class MyClass:
    def __init__(self, x, y):
        """Input variables are two large data arrays"""
        self.x = x
        self.y = y

    @property
    def calculate(self):
        """Some computationally expensive operation"""
        try:
            # the result has been calculated already
            return self._result
        except AttributeError:
            # if not, calculate it
            self._result = self.x * self.y
            return self._result
Run Code Online (Sandbox Code Playgroud)

用法:

>>> foo = MyClass(2,3)
>>> a = foo.calculate
>>> print(a)
6
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,到目前为止我提出的所有内容都是存储结果的"隐藏"属性.有一个更好的方法吗?@property这里使用正确吗?

谢谢.

python oop class

5
推荐指数
1
解决办法
108
查看次数

标签 统计

python ×2

cartopy ×1

class ×1

matplotlib ×1

oop ×1

subplot ×1