I would like to know if it possible to save matplotlib animation with lossless quality (or even vectorial format)
I have the following animation from matplotlib examples
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return ln,
def update(frame):
xdata.append(frame)
ydata.append(np.sin(frame))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
init_func=init, blit=True)
plt.show()
I found this post from 2013 Can matplotlib animation output vector sequence? and at the time it was not possible.
Has anything changed and is it now possible to output the data into vector-like format?
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()
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?
ipython notebook 3.0.0
matplotlib 1.4.3
OS X 10.11.4
I am creating an interactive 3D scatter plot of a 3D data cube.
I've included here a toy example that generates the same problems I am encountering trying to plot my data cube.
If I generate a matplot window outside of the notebook, when I manually close it (clicking the red x) it stalls with 'the wheel' until I force quit.
#Generate matplot window outside of the notebook
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
#from matplot3d tutorial
def randrange(n, vmin, vmax):
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure() ax = fig.add_subplot(111, projection='3d') n = 100 for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label')
plt.show()
I've tried using mpld3 within the notebook but a non-interactive image displays along with the error
"TypeError: array([ 2., 20.]) is not JSON serializable"
#Use mpld3 within notebook
import matplotlib.pyplot as plt
import numpy as np
import mpld3
from mpl_toolkits.mplot3d import Axes3D
mpld3.enable_notebook()
def randrange(n, vmin, vmax):
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zl, zh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
Some quick research into JSON serialization has been non-fruitful.
What is the best way to create an interactive 3D matplotlib scatter plot that won't stall?
In IPython, even if you aren't using the inline backend, it's best to use %matplotlib. This tells IPython and matplotlib to work together with eventloops and should help with the hang. To use the default GUI backend, use:
%matplotlib
Or to specify the qt backend:
%matplotlib qt
This avoids the need for plt.show() and the blocking of the kernel when plots are being drawn.
For best results, run this in he first cell of your notebook, on its own before any plotting commands.
I have three lists xs, ys, zs of data points in Python and I am trying to create a 3d plot with matplotlib using the scatter3d method.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.xlim(290)
plt.ylim(301)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(xs, ys, zs)
plt.savefig('dateiname.png')
plt.close()
The plt.xlim() and plt.ylim() work fine, but I don't find a function to set the borders in z-direction. How can I do so?
Simply use the set_zlim function of the axes object (like you already did with set_zlabel, which also isn't available as plt.zlabel):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
xs = np.random.random(10)
ys = np.random.random(10)
zs = np.random.random(10)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(xs, ys, zs)
ax.set_zlim(-10,10)