plotting streamplot is so slow in python3 - python

I am using Anaconda, and I think this problem is even before I use Anaconda.
Everytime I want to plot streamline with basemap, it takes a very long time to plot one figure.
Here is an example:
import netCDF4 as nc
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap
fuv = nc.Dataset('~/era5_uv850_20200601_00_01.nc')
uwnd = fuv.variables['u']
vwnd = fuv.variables['v']
uwnd = uwnd[0,:,:]
vwnd = vwnd[0,:,:]
lon= fuv.variables['longitude']
lat= fuv.variables['latitude']
map = Basemap(projection='cyl',llcrnrlat= 0.,urcrnrlat=20.,llcrnrlon=90.5,urcrnrlon=120.5,resolution='i')
x,y=map(*np.meshgrid(lon,lat))
plt.clf()
map.streamplot(x,y,uwnd,vwnd,30)
map.drawcoastlines()
map.drawcountries()
plt.show()
The data from ERA5 webpage: Copernicus Data Storage
or you can download it here: WeTransfer Link
Is the slowness a common issue?

Related

Using missing_kwds with geopandas changes the shape of the displayed map

I'm using Geopandas (0.11.1) to plot data on maps. I'm facing an issue with missing_kwds. As some of my values are undefined, I want them to be colored in a specific way. I do that using the missing_kwds option of the plot method.
However, when using it, the shape of the map slightly changes, which is disgraceful when switching quickly from one to the other.
Here is an example.
A map without using missing_kwds :
import geopandas
import matplotlib.pyplot as plt
df = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
df.plot()
plt.savefig('world1.png')
A map using missing_kwds :
import geopandas
import matplotlib.pyplot as plt
import numpy as np
df = geopandas.read_file(geopandas.datasets.get_path("naturalearth_lowres"))
df.loc[df.name=="China", 'pop_est'] = np.nan
df.plot(column="pop_est", missing_kwds=dict(color="lightgray"))
plt.savefig('world2.png')
Those are the two resulting maps.
world1.png:
world2.png:
In case the difference isn't clear, here is a GIF that illustrates the shape changes.
Does anyone have an idea how I could solve this issue?
Add plt.gca().set_aspect('equal') after df.plot().

How to export a 3D plot using tikzplotlib and import it in LaTeX?

Consider following code (adapted from here):
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import tikzplotlib
r=np.linspace(0,1,11)
theta=np.linspace(0,2*np.pi,11)
R,Theta=np.meshgrid(r,theta)
X,Y=R*np.cos(Theta),R*np.sin(Theta)
Z=R*np.sin(Theta)*np.cos(Theta)
fig=plt.figure(1)
plt.clf()
ax=fig.add_subplot(projection='3d')
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.inferno,linewidth=0)
ax.set_xlabel('test here')
plt.show()
tikzplotlib.save("testfigure.tex")
which gives following figure :
When I import the file testfigure.tex in a LaTeX file, after having replaced
\begin{axis}[
hide x axis,
hide y axis,
by
\begin{axis}[
width=10cm,
width=10cm,
I obtain this result :
What can I do, in order to have the axis as in the Python figure? Or is this simply not possible with tikzplotlib?
Github Readme of tikzplotlib states 3D plots are not supported (2021).
Tikzplotlib - Github

box plot not appearing in Google Colab

Trying to create a simple Box Plot using Google Colab for my Intro Python class. It is not appearing as I would like it. You can see my code and output below. I read in a file on NBA statistics, and my box plot would be based on a variable called "SHOT_CLOCK".
So far what I have:
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('file path')
plt.boxplot(df['SHOT_CLOCK'], vert=False)
plt.title('Box Plot for SHOT_CLOCK')
plt.xlabel('Shot Clock')
plt.show()
Output:
Edit
In your example you are passing a Series object, try this way
plt.figure()
plt.title('Box Plot for SHOT_CLOCK')
plt.xlabel('Shot Clock')
df.boxplot(column='SHOT_CLOCK')
Once you add the following Import to your code it will work:
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline

How do you log stretch a FITS image and change its contrast?

I'm trying to use astropy 2.0.11 with python 2.7.15 to edit a fits image by applying a log stretch to it and change the contrast, and I have't been able to figure it out.
I've been trying to follow the tutorials on the astropy website for opening and manipulating fits files, but I'm wondering if the tutorials will only work for the latest version of astropy and on python 3?
Sorry about the organization of my code. This is prototype code and I'm just trying to test a few things and get this to work.
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import astropy.visualization
from astropy.io import fits
from astropy.utils.data import download_file
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
def main():
#My own fits file
#fitsImage = get_pkg_data_filename("C:\\20180807T000456.fits")
fitsImage = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits', cache=True )
hdu_list = fits.open(fitsImage)
hdu_list.info()
#norm = ImageNormalize(stretch=LogStretch())
image_data = fits.getdata(fitsImage)
print(type(image_data))
print(image_data.shape)
hdu_list.close()
plt.figure()
plt.imshow(image_data, cmap='gray', norm=LogNorm())
plt.colorbar()
# I chose the tick marks based on the histogram above
cbar = plt.colorbar(ticks=[5.e3,1.e4,2.e4])
cbar.ax.set_yticklabels(['5,000','10,000','20,000'])
time.sleep(10)
I am also unable to get the image to display with the plt.imshow()
Any insight would be helpful
You're so close! I ran your code in Python 2.7 and all you need to do is add
plt.show()
before time.sleep(10) (any reason you're including this?) and you get
Also, I don't think you need to include the colorbar and yticklabels, plt.imshow automatically adds the colorbar with the lognorm scale (I commented that section out when I got the image).

matplotlib fails to output EPS figure with usetex = True

I am trying to output (savefig) matplotlib figures as EPS; however, it seems there is a conflict when using the LaTeX rendering AND saving EPS figures. For example, the following code produces a good EPS figure:
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.plot(np.random.rand(100))
plt.savefig('plot.eps')
whereas this code produces an EPS figure that can not be viewed; my document viewer (Ubuntu's Evince) continuously says "Loading..."
import matplotlib.pyplot as plt
import numpy as np
plt.rc('text', usetex = True)
plt.figure()
plt.plot(np.random.rand(100))
plt.savefig('plot.eps')
Is there a known issue when combining these two options? Is there any kind of work around (aside from saving as PDF or saving as PDF then converting to EPS)?
The only solution I could find was to update matplotlib from 1.2.1 to 1.3.1. Now it works without problems.

Categories