简体   繁体   English

matplotlib斧到数字范围-删除空白,边框和所有关于Geopandas地图的图

[英]matplotlib ax to figure extent - remove whitespace, borders, everything for plot of geopandas map

I am looking for a solution to have a seamless map image plot with matplotlib. 我正在寻找一种具有matplotlib的无缝地图图像的解决方案。 The current code works good and stable, however, it leaves a whitespace to the left and bottom. 当前代码运行良好且稳定,但是,它在左侧和底部留有空白。 I would like to remove this whitespace and don't know how. 我想删除此空格,不知道如何。

My sample code for this: 我的示例代码:

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)

sample.png sample.png

smaple.png with marked whitespace I would like to remove smarkle.png带有标记的空格,我想删除

I followed the Tutorial at Matplotlib's Tight Layout guide , machinelearningplus.com , Removing white padding from figure on Reddit as well as several other stackoverflow posts, namely 我跟着教程在Matplotlib的布局紧凑指导machinelearningplus.com除去在Reddit上图白填料以及其他几个计算器的帖子,即

Matplotlib scatter plot - Remove white padding , Matplotlib散点图-删除白色填充

Matplotlib: Getting subplots to fill figure , Matplotlib:获取子图来填充图形

Matplotlib plots: removing axis, legends and white spaces , Matplotlib图:删除轴,图例和空白

Removing white space around a saved image in matplotlib 在matplotlib中删除已保存图像周围的空白

and

matplotlib plot to fill figure only with data points, no borders, labels, axes, matplotlib图以仅用数据点,无边界,标签,轴,

What am I missing? 我想念什么?


edit - to provide a reproducable version with non-real-life data, but question stays the same - how do I get rid of the whitespace around my plot? 编辑-提供具有非真实数据的可重现版本,但问题仍然存在-我如何摆脱剧情周围的空白?

I am new to Geopandas, so I am not sure how to recreate a geodataframe, however, there is built in datasets with it. 我是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')

First there is a difference when using different geopandas versions. 首先,使用不同的geopandas版本会有所不同。 One should probably make sure to use geopandas 0.4 at least to have the map in the correct aspect ratio. 人们可能应该确保至少使用geopandas 0.4才能使地图具有正确的纵横比。

Next one needs to remove the padding inside the axes. 下一步需要删除轴的填充。 This can be done using the ax.margins(0) command. 可以使用ax.margins(0)命令来完成。

Now this would lead to some whitespace in one direction (top and bottom in this case). 现在,这将导致一个方向上的空白(在这种情况下为顶部和底部)。 One option is to shrink the figure to the extent of the axes. 一种选择是将图形缩小到轴的范围。

import numpy as np
import matplotlib; print(matplotlib.__version__)
import matplotlib.pyplot as plt
import geopandas; print(geopandas.__version__)

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')

world.plot(ax=ax, column='2015', scheme='quantiles')

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)

plt.savefig('sample.png')
plt.show()

The advantage of this is that the physical size of the figure really fits the axes; 这样做的好处是图形的物理尺寸真正适合轴。 so the result is the same whether shown on screen or saved as image. 因此无论在屏幕上显示还是另存为图像,结果都是相同的。

If instead the aim is to just save the figure without whitespace you can use the bbox_inches argument to savefig and supply the actual extent of the axes in inches. 如果相反的目的是仅保存图形而不bbox_inches空格,则可以使用bbox_inches参数savefig并以英寸为单位提供轴的实际范围。

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

world.plot(ax=ax, column='2015', scheme='quantiles')

ax.margins(0)
ax.apply_aspect()
bbox = ax.get_window_extent().inverse_transformed(fig.dpi_scale_trans)

plt.savefig('sample.png', bbox_inches=bbox)

Finally, the above can be automated, using bbox_inches='tight' . 最后,可以使用bbox_inches='tight'自动化上述操作。 However, for the 'tight' option to work correctly, one will need to make sure there are no ticks and labels around the axes, which would otherwise increase the spacing. 但是,为使'tight'选项正常工作,需要确保轴周围没有刻度线和标签,否则会增加间距。

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

world.plot(ax=ax, column='2015', scheme='quantiles')

ax.margins(0)
ax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)

plt.savefig('sample.png', bbox_inches="tight", pad_inches=0)

In all three cases above, the resulting figure would be 在上述所有三种情况下,得出的数字将是

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM