Matplotlib 在geopandas中,在地图周围添加边距
我似乎无法解决GeoPandas地图和添加注释之间的一些边距/位置问题。注释是由函数Matplotlib 在geopandas中,在地图周围添加边距,matplotlib,geopandas,Matplotlib,Geopandas,我似乎无法解决GeoPandas地图和添加注释之间的一些边距/位置问题。注释是由函数addChartSignature和addTitle添加的,它们会导致糟糕的布局 我已经成功地用黑客对一些垂直边距问题进行了排序,请参见注释####以处理垂直边距问题,但是我似乎无法处理左侧的边距:我希望地图、签名和标题与左侧对齐,并留有很小的边距(如右侧) 我添加了变量rightspace,以将注释向右移动,但它没有帮助,而且感觉也不对劲 下面是总结问题的代码示例 from __future__ import
addChartSignature
和addTitle
添加的,它们会导致糟糕的布局
我已经成功地用黑客对一些垂直边距问题进行了排序,请参见注释####以处理垂直边距问题
,但是我似乎无法处理左侧的边距:我希望地图、签名和标题与左侧对齐,并留有很小的边距(如右侧)
我添加了变量rightspace
,以将注释向右移动,但它没有帮助,而且感觉也不对劲
下面是总结问题的代码示例
from __future__ import division
import matplotlib.pyplot as plt
import geopandas
from mpl_toolkits.axes_grid1 import make_axes_locatable
def addChartSignature(ax, vspace=0, righthspace=0):
ax.annotate('',
xy=(0.97, 0.05 + vspace),
xycoords='figure fraction',
xytext=(0.03 + righthspace,0.05 + vspace),
textcoords='figure fraction',
arrowprops=dict(arrowstyle="-",
linewidth=0.7,
facecolor='grey',
alpha=.7,
edgecolor='grey'),
horizontalalignment = 'center',
verticalalignment='bottom')
ax.annotate(u" ©myCompany",
xy=(0.5, 0.5),
xycoords='figure fraction',
xytext= (0.03 + righthspace,0.01+vspace),
textcoords='figure fraction',
ha="left",
va="bottom",
color = 'grey',
alpha = .7,
fontsize = 11)
ax.annotate(u"Source: Internal",
xy=(0.5, 0.5),
xycoords='figure fraction',
xytext=(0.97,0.01+vspace),
textcoords='figure fraction',
ha="right",
va="bottom",
color = 'grey',
alpha = .7,
fontsize = 11)
def addTitle(ax, vspace=0, righthspace=0):
ax.annotate("My Chart Title",
xy=(0.5, 0.5),
xycoords='figure fraction',
xytext=(0.01+righthspace, 0.985+vspace),
textcoords='figure fraction',
ha="left",
va="top",
color = 'black',
alpha = .75,
fontsize = 19,
weight = 'bold')
path = geopandas.datasets.get_path('naturalearth_lowres')
world = geopandas.read_file(path)
world = world[(world.pop_est>0) & (world.name!="Antarctica")]
plt.style.use('fivethirtyeight')
fig = plt.figure(figsize=(8, 6))
ax = fig.add_axes([0., 0., 1, 1])
ax = world.plot(color="lightgrey", ax=ax)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="3%", pad=-1.3)
world.dropna().plot(
column='pop_est',
ax=ax,
legend=True,
cax=cax,
cmap='RdYlGn',
)
ax.grid(color='#F8F8F8')
ax.set_xticklabels([])
ax.set_yticklabels([])
### to deal with vertical margin issue
ax.set_aspect(aspect=4./3)
ax.margins(0)
ax.apply_aspect()
bbox = ax.get_window_extent().inverse_transformed(fig.transFigure)
w,h = fig.get_size_inches()
fig.set_size_inches(w*bbox.width, h*bbox.height)
addChartSignature(ax, righthspace = 0.05)
addTitle(ax, righthspace = 0.05)
左侧实际上是问题最少的一侧,因为所有艺术家都可以在一个坐标系中完美对齐。它只是因为用于垂直方向的“hack”而被扰乱了。这里的总体问题是,要使所有对象完全对齐,并调整图形大小使其适合,同时保持轴的固定方向,这是非常困难的。没有一个通用的解决方案。但人们当然可以用显微镜计算所有参数。我只是不确定是否有人愿意在这里给出答案。@ImportanceOfBeingErnest感谢您的反馈。这是我自己能想出的最好办法。但如果将其删除,绘图将成为带有注释的简单geopandas地图。我不明白为什么很难将这些物体完全对齐