【发布时间】:2019-08-04 02:45:11
【问题描述】:
我正在寻找使用 matplotlib 绘制无缝地图图像的解决方案。当前的代码运行良好且稳定,但是它在左侧和底部留下了一个空格。我想删除这个空格,不知道怎么做。
我的示例代码:
import geopandas
from seaborn import despine
from pandas import read_csv
import matplotlib.pyplot as plt
# read data and shapefile
geo_path = 'shapefiles/ne_10m_admin_0_countries.shp'
df = read_csv('UNpopEstimates2100.csv')
world = geopandas.read_file(geo_path)
# specifiy what is to be plotted
cm = 'Greys'
world['2015'] = df['2015']
# set plot environment
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
world.plot(ax=ax, column='2015', cmap=cm, scheme='quantiles')
plt.savefig('sample.png', bbox_inches='tight', tight_layout=True, pad_inches=0, frameon=None)
smaple.png with marked whitespace I would like to remove
我在 Matplotlib's Tight Layout guide、machinelearningplus.com、Removing white padding from figure on Reddit 以及其他几个 stackoverflow 帖子上关注了教程,即
Matplotlib scatter plot - Remove white padding,
Matplotlib: Getting subplots to fill figure,
Matplotlib plots: removing axis, legends and white spaces,
Removing white space around a saved image in matplotlib
和
matplotlib plot to fill figure only with data points, no borders, labels, axes,
我错过了什么?
编辑 - 提供具有非真实数据的可重现版本,但问题保持不变 - 我如何摆脱情节周围的空白?
我是 Geopandas 的新手,所以我不知道如何重新创建地理数据框,但是,它有内置的数据集。
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world['2015'] = np.random.uniform(low=1., high=100., size=(177,))
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
world.plot(ax=ax, column='2015', scheme='quantiles')
plt.savefig('sample.png')
【问题讨论】:
-
到目前为止我可以添加的东西,因为我试过了: - ax.set_xlim() 和 ax.set_ylim() 调整图像的位置和范围,但留下完全相同的空白 - plt.margins (x=0, y=0) 在这种情况下不会产生任何影响 - fig.subplots_adjust(wspace=0) 和 fig.subplots_adjust(hspace=0) 删除多个子图之间的空白,但这是一个单独的子图,所以它没有帮助 - ax.axis('off') 和 ax.set_axis_off() 接缝具有完全相同的效果 - 在代码中或在绘图之前重复 plt.tight_layout() 没有显示任何改进
-
plt.savefig('sample.png')的结果是什么?这与你的追求相差多远? -
@ImportanceOfBeingErnest 它为所有四个边留下了一个均匀的空白,明显更宽。
-
如果四个边都有空格,那就奇怪了。你能让代码可重现吗(见minimal reproducible example,可能不需要真实世界的数据?)?
-
@ImportanceOfBeingErnest 上面的编辑是否更适合您?感谢您的输入!注意:即使我使用以前的
plt.savefig('sample.png', bbox_inches='tight', tight_layout=True, pad_inches=0, frameon=None)也无济于事。
标签: python matplotlib plot removing-whitespace geopandas