Plotting a map with matplotlib basemap - horribly slow - python

Plotting a very, very simple map of only europe in matplotlib / basemap takes so much time (around 10 seconds!). This is just unreal!?
Setting of resolution is only "l" (low).
Here is the very simple code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
m = Basemap(projection='stere',lon_0=5,lat_0=90.0,rsphere=6371200.,\
llcrnrlon=-25.0,urcrnrlon=72.0,llcrnrlat=26.0,urcrnrlat=65.0,resolution='l')
m.drawcoastlines(linewidth=0.2)
m.drawcountries(linewidth=0.2)
plt.savefig('/var/www/map.png')
I need to plot hundreds of these maps every 2 hours. This would be impossible? :( Only idea is: Create an empty Basemap and try to draw boundaries with a shapefile.
Regards,
John

Related

Saving a plot from multiple subplots

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,foo-function)
now I need a way to save each of the 4 plots into one file like this:
plt1=topleft_plot.saveNOTfigBUTplot('quadfunction.pdf')
how?
Using the answer here: https://stackoverflow.com/a/4328608/16299117
We can do the following to save a SINGLE subplot from the overall figure:
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
# I am not using jupyter notebook, so I use this to show it instead of %inline
plt.show()
# Getting only the axes specified by ax[0,0]
extent = ax[0,0].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
# Saving it to a pdf file.
fig.savefig('ax2_figure.pdf', bbox_inches=extent.expanded(1.1, 1.2))
EDIT: I believe I may have misunderstood what you want. If you want to save EACH plot individually, say as 4 different pages in a pdf, you can do the following adapted from this answer: https://stackoverflow.com/a/29435953/16299117
This will save each subplot from the figure as a different page in a single pdf.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
fig,ax=plt.subplots(2,2,figsize=(15,10))
x=np.linspace(-3,3)
ax[0,0].plot(x,x**2) # This is just to make an actual plot.
with PdfPages('foo.pdf') as pdf:
for x in range(ax.shape[0]):
for y in range(ax.shape[1]):
extent = ax[x, y].get_window_extent().transformed(fig.dpi_scale_trans.inverted())
pdf.savefig(bbox_inches=extent.expanded(1.1, 1.2))

I am trying to color code the plot circles in my scatter plot and reference to the legend. The data is via a csv file

Sample result I want to color code the circle plots in my scatter and associate them with a legend.
I have made various attempts at a solution referencing matplotlib.org and this website. All to no avail.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
hysector = pd.read_csv('LF98TRUU_Lvl3_sector.csv',index_col=0)
hysector.plot.scatter(x='OAD',y='OAS',s=hysector['Wgt']*35,label='Sector');

Plotting a graph takes a long time in Python

For plotting 100,000 to 500,000 data point in a text file I use the following code.
The problem is:
If I copy and paste the data points in a plotting software, reaching the plot takes just 30 seconds but with the following code it may take 1 hour or more to plot by Python.
import numpy as np
import matplotlib.pyplot as plt
from math import *
cmin=502.8571071527562
c,O=np.genfromtxt('textfile.txt',unpack=True)
for i in range(len(O)):
q=exp(-0.5*(c[i]-cmin))
plt.plot(O[i], q, 'bo')
plt.show()
What is the problem? How could I solve it?
I appreciate your help.
Some general rules:
use numpy, not math
avoid for-loops
Do not create unnecessary artists.
Here you want to create a single artist with all points, instead of 500000 single artists with one point each.
import numpy as np
import matplotlib.pyplot as plt
cmin=502.8571071527562
c,O=np.genfromtxt('textfile.txt',unpack=True)
q=np.exp(-0.5*(c-cmin))
plt.plot(O, q, 'bo')
plt.show()

Basemap Returns a Blank Map

I'm trying to animate a heat map of some information regarding geographic locations in Pittsburgh using matplotlib and basemap in Python 3. Right now I'm having issues getting basemap to use ARCGis imagery as the background. The following code only produces a blue square
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
m =Basemap(llcrnrlon=40.361369,llcrnrlat=-80.0955278,
urcrnrlon=40.501368,urcrnrlat=-79.865723,epsg=2272)
m.arcgisimage(service='ESRI_StreetMap_World_2D', xpixels=7000,dpi=96,verbose=True)
I've pulled down and run several examples from the internet about how to use arcgis images with basemap and they have run so I'm pretty sure its not a connection issue. I've tried several different projections and EPSG's including the world and US EPSGs, but no luck. Any help would be appreciated.
You have the longitudes and latitudes mixed up (see here):
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
m = Basemap(
llcrnrlat=40.361369, llcrnrlon=-80.0955278,
urcrnrlat=40.501368, urcrnrlon=-79.865723,
epsg = 2272
)
m.arcgisimage(service='ESRI_StreetMap_World_2D', xpixels=7000, verbose=True)
plt.show()
produces this image:

Basemap drawcountries() not working

I'm simply trying to plot a map and add the borders of the countries.
Here is the code snipped:
map=Basemap(projection="lcc",resolution="l",width=1E6,height=1E6,lon_0=9.9167,lat_0=51.5167,fix_aspect=False)
map.drawcounties(zorder=1,color="black")
map.shadedrelief()
map.drawcoastlines(color="black",linewidth=2)
map.drawrivers(linewidth=0.5,color="blue")
map.drawmapboundary()
Everything is working besides the borders....There is also no
Error...it simply does nothing.
What am I doing wrong?
Additionaly the resolution of the map is a bit blurred. Is there any way to boost the resolution?
Thanks for your answers!!!
To draw to borders of the countries you need drawcountries. (Mind the r)
To draw to borders of the counties you need drawcounties.
Note however that the german Bundesländer are no "counties" in the sense of the basemap, so it will not draw them.
To get a higher resolution try resolution="i" in the Basemap initialization.
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
map=Basemap(projection="lcc",resolution="i",width=1E6,height=1E6,
lon_0=9.9167,lat_0=51.5167,fix_aspect=False)
map.drawcountries(zorder=1,color="black", linewidth=1)
map.shadedrelief()
map.drawcoastlines(color="black",linewidth=1.2)
map.drawrivers(linewidth=0.5,color="blue")
map.drawmapboundary()
plt.show()

Categories

Resources