I am currently plotting precipitation from a netcdf dataset. When I plot my data a line of no data appears which isn't there is a different plot I made. Here is my code:
import matplotlib.pyplot as plt
from netCDF4 import Dataset as netcdf_dataset
import numpy as np
from cartopy import config
import cartopy.crs as ccrs
fig = plt.figure(figsize=(20,5))
dataset = netcdf_dataset(datapath_1 +
'/PREC.E_2000_CAM5_1850aero.cam.mean.40-100.nc')
precip = dataset.variables['PREC'][0, :, :]
lats = dataset.variables['lat'][:]
lons = dataset.variables['lon'][:]
ax = plt.axes(projection=ccrs.Robinson())
ax.contourf(lons, lats, precip, 100, transform=ccrs.PlateCarree())
ax.coastlines()
plt.show()
and here is the output map:
output map
You may need to add a cyclic point to your data array and longitude coordinate (https://scitools.org.uk/cartopy/docs/v0.16/cartopy/util/util.html#cartopy.util.add_cyclic_point). Your example modified to do this (but not tested because we don't have your input data):
import matplotlib.pyplot as plt
from netCDF4 import Dataset as netcdf_dataset
import numpy as np
from cartopy import config
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
dataset = netcdf_dataset(datapath_1 +
'/PREC.E_2000_CAM5_1850aero.cam.mean.40-100.nc')
precip = dataset.variables['PREC'][0, :, :]
lats = dataset.variables['lat'][:]
lons = dataset.variables['lon'][:]
precip_c, lons_c = add_cyclic_point(precip, coord=lons)
fig = plt.figure(figsize=(20,5))
ax = plt.axes(projection=ccrs.Robinson())
ax.contourf(lons_c, lats, precip_c, 100, transform=ccrs.PlateCarree())
ax.coastlines()
plt.show()
Related
You can see I am using ax.plot but nothing happened.
Just call plt.show() when you've run all of your graph creation code:
import numpy as np
import matplotlib.pyplot as plt
x= np.arange(-10, 10, 0.1)
fig, ax = plt.subplots()
ax.plot(x, np.cos(x))
plt.show()
I am working on imbalanced classification. I wanted to add g-mean, and accuracy in my decision boundary plot. It would be nice to see the differences of these scoring metrics in plot. I don't see any option to compute these scores within this decision boundary plot. Is there way I can add this extra information in my decision boundary plot. I appreciate your time. Thanks!
import numpy as np
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_decision_regions
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_blobs
from sklearn.metrics import make_scorer
from imblearn.metrics import geometric_mean_score
from mlxtend.plotting import plot_decision_regions
import matplotlib.gridspec as gridspec
import itertools
gmean = make_scorer(geometric_mean_score, greater_is_better=True)
scoring = {'G-mean': gmean, 'Accuracy':'accuracy'}
X, y = make_blobs(n_samples=[1000, 10],centers=[[0.0, 0.0], [2.0, 2.0]],cluster_std= [1.5, 0.5],random_state=0, shuffle=False)
clf1 = LogisticRegression(max_iter=100000)
clf2 = LogisticRegression(class_weight="balanced",max_iter=100000)
gs = gridspec.GridSpec(2, 2)
fig = plt.figure(figsize=(10,8))
labels = ['Logistic Regression', 'Weighted Logistic Regression']
for clf, lab, grd in zip([clf1, clf2],
labels,
itertools.product([0, 1], repeat=2)):
clf.fit(X, y)
ax = plt.subplot(gs[grd[0], grd[1]])
fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)
plt.title(lab)
plt.show()
You can use plt.text() to add g-mean, and accuracy in your decision boundary plot.
For example:
gs = gridspec.GridSpec(2, 2)
fig = plt.figure(figsize=(15, 8))
labels = ['Logistic Regression', 'Weighted Logistic Regression']
for clf, lab, grd in zip([clf1, clf2],
labels,
itertools.product([0, 1], repeat=2)):
clf.fit(X, y)
ax = plt.subplot(gs[grd[0], grd[1]])
ax.text(6, 4, "gmean : ", fontsize=10)
ax.text(6, 2, "accuracy : ", fontsize=10)
fig = plot_decision_regions(X=X, y=y, clf=clf, legend=2)
plt.title(lab)
plt.show()
Is it possible to save and load the plot with all its attributes? E.g. pickle the Figure instance and then opening it in another script and redrawing as it was in the original script.
Script1
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.figure()
pd.to_pickle(fig,'fig.pkl')
Script2
import matplotlib.pyplot as plt
import pandas as pd
fig = pd.read_pickle(fig,'fig.pkl')
# Now plot it so that it looks like in script1
You can use pickle.dump to save:
import matplotlib.pyplot as plt
import pickle
fig, ax = plt.subplots()
pickle.dump(fig, open('fig.pkl', 'wb'))
And pickle.load to recover:
import matplotlib.pyplot as plt
import pickle
fig = pickle.load(open('fig.pkl', 'rb'))
plt.show()
Re: comment about storing figs in a dict
This works on my end -- dump the dict of figure handles:
import matplotlib.pyplot as plt
import pickle
fig1, ax1 = plt.subplots()
ax1.plot([0, 1], [0, 1])
fig2, ax2 = plt.subplots()
ax2.plot([1, 0], [0, 1])
figs = {'fig1': fig1, 'fig2': fig2}
pickle.dump(figs, open('figs.pickle', 'wb'))
Then load the dict and access the desired dict key:
import matplotlib.pyplot as plt
import pickle
figs = pickle.load(open('figs.pickle', 'rb'))
figs['fig1'] # or figs['fig2']
Below is the code to build a standalone continuous colorbar. I would like to mask, with black, all values between -3 and 3.
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(8, .25))
cmap = mpl.cm.twilight
norm = mpl.colors.Normalize(vmin=-9.6, vmax=9.6)
cbar = mpl.colorbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal', ticks=[-3,3])
The function colors.ListedColormap creates a new colormap from a list of colors. The following code retrieves these colors from an existing map and makes the desired modifications:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
cmap = mpl.cm.get_cmap('twilight', 256)
norm = mpl.colors.Normalize(vmin=-9.6, vmax=9.6)
maskedcolors = cmap(np.linspace(0, 1, 256))
black = np.array([0, 0, 0, 1])
maskedcolors[int(round(norm(-3) * 256)) : int(round(norm(3) * 256)) + 1] = black
maskedcmp = mpl.colors.ListedColormap(maskedcolors)
fig, ax = plt.subplots(figsize=(8, .5))
cbar = mpl.colorbar.ColorbarBase(ax, cmap=maskedcmp, norm=norm, orientation='horizontal', ticks=[-3, 3])
fig.subplots_adjust(bottom=0.5)
plt.show()
The following code works fine to save an animation to file:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, bitrate=1800)
fig, ax = plt.subplots()
ims = []
x = np.linspace(0, np.pi,200)
for theta in np.linspace(0, np.pi, 50):
plot = ax.plot(x, np.sin(x + theta))
ims.append(plot)
im_ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True)
im_ani.save('im.mp4', writer=writer)
Now, I would like to view the animation interactively as the plots are generated, while still saving it to file. I therefore tried the following code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, bitrate=1800)
plt.ion()
fig, ax = plt.subplots()
ims = []
x = np.linspace(0, np.pi, 200)
for theta in np.linspace(0, np.pi, 50):
ax.clear()
plot = ax.plot(x, np.sin(x + theta))
ims.append(plot)
plt.draw()
plt.pause(0.01)
im_ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True)
im_ani.save('im.mp4', writer=writer)
which lets me view the animation interactively, but the resulting video file contains only blank frames.
Is is possible to view an animation interactively and save it to file at the same time? What is the issue with my code?