Export Python Plot to KML
How to create a lon / lat plot with Matplotlib that can be exported to Google Earth with the points appearing on GE correctly. The image can be viewed here: http://imgur.com/4szLzNF There always seems to be a small border around my exported number, so the points I define in the graph are disabled in GE
x = [0, 10, 10, 0, 0]
y = [10, 10, 0, 0, 10]
x1=[0,1,2,3,4,5,6,7,8,9,10]
fig = Figure(facecolor=None, frameon=False)
ax = fig.add_axes([0,0,1,1])
ax.axis('off')
ppl.plot(x, y, 'r', axes=ax)
ppl.plot(x, y, '.b', axes=ax)
ppl.plot(x1, x1, 'g', axes=ax)
ppl.axis('off')
ppl.tight_layout(0,h_pad=0, w_pad=0)
border1 = ppl.axis(bbox_inches='tight')
ppl.show()
pngName = 'temp.png'
py.savefig(pngName, bbox_inches='tight', pad_inches=0, transparent=True)
bottomleft = (border1[0],border1[2])
bottomright = (border1[1],border1[2])
topright = (border1[1],border1[3])
topleft = (border1[0],border1[3])
kml = simplekml.Kml()
ground = kml.newgroundoverlay(name='GroundOverlay')
ground.icon.href = pngName
ground.gxlatlonquad.coords =[bottomleft, bottomright, topright, topleft]
kml.save("GroundOverlay_temp.kml")
source to share
I have a solution, but I'm not familiar enough with the Figure and Artist classes to give a clear explanation of why this is correct.
You need to do the following two things:
- Use
fig = ppl.figure()
insteadmatplotlib.figure.Figure()
. - Save with
fig.savefig()
insteadppl.savefig()
.
Also the use of tight_layout and padding is not required. I also set the facecolor for the shape so that I can see the true borders. View the output image, temp.png, with an image viewer and you will see that the rectangle's borders are at the edges of the shapes; when I ran your source code and viewed the image, there was always a small space between the borders of the rectangle and the shape.
Here's the fixed code:
import matplotlib
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as ppl
from pylab import rcParams
import simplekml
rcParams['figure.figsize'] = (8,8)
# create rectangle over 0 to 10 degrees longitude and 0 to 10 degrees latitude
x = [0, 10, 10, 0, 0]
y = [10, 10, 0, 0, 10]
x1=range(0,11) # to draw a diagonal line
fig = ppl.figure(1)
ax = fig.add_axes([0,0,1,1])
ax.axis('off')
fig.patch.set_facecolor('blue') # so we can see the true extent
ppl.plot(x, y, 'r', linewidth=3)
ppl.plot(x, y, '.b', linewidth=3)
ppl.plot(x1, x1, 'g', linewidth=3)
ppl.axis('off')
border1 = ppl.axis()
print 'Border = %s' %(str(border1))
if False:
ppl.show()
else:
pngName = 'Overlay.png'
fig.savefig(pngName, facecolor=fig.get_facecolor(), transparent=False)
bottomleft = (border1[0],border1[2])
bottomright = (border1[1],border1[2])
topright = (border1[1],border1[3])
topleft = (border1[0],border1[3])
kml = simplekml.Kml()
ground = kml.newgroundoverlay(name='GroundOverlay')
ground.icon.href = pngName
ground.gxlatlonquad.coords =[bottomleft, bottomright, topright, topleft]
kml.save("GroundOverlay.kml")
source to share