warning about too many open figures

Use .clf or .cla on your figure object instead of creating a new figure. From @DavidZwicker Assuming you have imported pyplot as import matplotlib.pyplot as plt plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. plt.clf() clears the entire current figure with all its axes, … Read more

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is: First ensure your NumPy array, myarray, is normalised with the max value at 1.0. Apply the colormap directly to myarray. Rescale to the 0-255 range. Convert to integers, using np.uint8(). Use Image.fromarray(). And you’re done: from PIL import Image from matplotlib import cm im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255)) with … Read more

matplotlib: how to draw a rectangle on image

You can add a Rectangle patch to the matplotlib Axes. For example (using the image from the tutorial here): import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image im = Image.open(‘stinkbug.png’) # Create figure and axes fig, ax = plt.subplots() # Display the image ax.imshow(im) # Create a Rectangle patch rect = … Read more

Reduce left and right margins in matplotlib plot

One way to automatically do this is the bbox_inches=”tight” kwarg to plt.savefig. E.g. import matplotlib.pyplot as plt import numpy as np data = np.arange(3000).reshape((100,30)) plt.imshow(data) plt.savefig(‘test.png’, bbox_inches=”tight”) Another way is to use fig.tight_layout() import matplotlib.pyplot as plt import numpy as np xs = np.linspace(0, 1, 20); ys = np.sin(xs) fig = plt.figure() axes = fig.add_subplot(1,1,1) … Read more

How to save a Seaborn plot into a file

The following calls allow you to access the figure (Seaborn 0.8.1 compatible): swarm_plot = sns.swarmplot(…) fig = swarm_plot.get_figure() fig.savefig(“out.png”) as seen previously in this answer. The suggested solutions are incompatible with Seaborn 0.8.1. They give the following errors because the Seaborn interface has changed: AttributeError: ‘AxesSubplot’ object has no attribute ‘fig’ When trying to access … Read more

Set markers for individual points on a line in Matplotlib

Specify the keyword args linestyle and/or marker in your call to plot. For example, using a dashed line and blue circle markers: plt.plot(range(10), linestyle=”–“, marker=”o”, color=”b”, label=”line with marker”) plt.legend() A shortcut call for the same thing: plt.plot(range(10), ‘–bo’, label=”line with marker”) plt.legend() Here is a list of the possible line and marker styles: ================ … Read more