添加后是否可以更改 cartopy 中对象的颜色?

Is it possible to change the color of an object in cartopy after it has been added?

问题

我正在使用 cartopy 在 Python 中绘制一些国家。为此,我使用 add_geometry 函数,如下所示:

geo = ax.add_geometries(geometry,facecolor='ghostwhite', edgecolor='black',crs=data_transf)

我希望能够更改已添加的几何对象的颜色。这样我就可以制作带有不同颜色的国家的动画,而无需每帧重新绘制所有内容。例如,国家开始都是白色的,然后一个接一个地变成蓝色。

但是,我似乎找不到在添加对象后更改对象颜色的方法。

通常有效的方法

使用 maplotlib 中的常规绘图,我会这样做:

import matplolib.pyplot as plt

line, = plt.plot([1,2,3],[4,5,6],'red') #Plot in red
line.set_color('green') #Change the color to green

为什么它在这里不起作用

没有 set_colorFeatureArtist 来自 cartopy 添加了 add_geometries 的函数。事实上,colorfacecolor、...属性似乎对于 FeatureArtist 甚至不存在,如对 matplotlib.artist.getp.[=25= 的调用所示]

对于剧情,调用returns:

>>import matplotlib.artist as mart
>>mart.getp(line)
agg_filter = None
alpha = None
animated = False
antialiased = True
children = []
clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
clip_on = True
clip_path = None
color = (1.0, 0.0, 0.0, 1.0)
contains = None
dash_capstyle = butt
dash_joinstyle = round
data = (array([1, 2, 3]), array([4, 5, 6]))
drawstyle = default
figure = Figure(640x476)
fillstyle = full
gid = None
in_layout = True
label = _line0
linestyle = -
linewidth = 1.5
marker = None
markeredgecolor = (1.0, 0.0, 0.0, 1.0)
markeredgewidth = 1.0
markerfacecolor = (1.0, 0.0, 0.0, 1.0)
markerfacecoloralt = none
markersize = 6.0
markevery = None
path = Path(array([[ 1.,  4.],        [ 2.,  5.],        ...
path_effects = []
picker = None
pickradius = 5
rasterized = None
sketch_params = None
snap = None
solid_capstyle = projecting
solid_joinstyle = round
transform = CompositeGenericTransform(     TransformWrapper(  ...
transformed_clip_path_and_affine = (None, None)
url = None
visible = True
xdata = [1 2 3]
xydata = [[ 1.  4.]  [ 2.  5.]  [ 3.  6.]]
ydata = [4 5 6]
zorder = 2

对于几何:

>>mart.getp(geo)
agg_filter = None
alpha = None
animated = False
children = []
clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
clip_on = True
clip_path = None
contains = None
figure = Figure(1200x990)
gid = None
in_layout = True
label = 
path_effects = []
picker = None
rasterized = None
sketch_params = None
snap = None
transform = CompositeGenericTransform(     TransformWrapper(  ...
transformed_clip_path_and_affine = (None, None)
url = None
visible = True
zorder = 1

如您所见,我无法更改 color属性(或类似)。

这绝对是Cartopy界面所欠缺的。你介意在 Cartopy issue tracker 上开个 issue 吗?

作为解决方法,您可以修改 private 属性 _kwargs,这似乎有效:

import cartopy.feature as cfeature
f = ax.add_feature(cfeature.STATES)
f._kwargs['edgecolor'] = 'blue'

注意: 这是使用私有 API,因此可能 change/break 没有任何警告。这只是让您行动起来的一种解决方法,但我强烈建议您报告该问题,以便将适当的解决方案添加到 Cartopy。