我似乎无法解决GeoPandas地图和添加的注释之间的某些边距/位置问题。注释是通过函数addChartSignature
和addTitle
添加的,它们引起了可怕的布局。
我设法用hack整理了一些垂直边距问题,请参见评论### to deal with vertical margin issue
,但是我似乎无法处理左侧的边距:我想要地图,签名和标题与左侧对齐,并且边距很小(如右侧)。
我添加了变量righthspace
以使注释正确移动,但是它无济于事,反正感觉也不对。
下面的代码示例总结了问题
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)