How to plot a histogram using Matplotlib in Python with a list of data?

If you want a histogram, you don’t need to attach any ‘names’ to x-values because: on x-axis you will have data bins on y-axis counts (by default) or frequencies (density=True) import matplotlib.pyplot as plt import numpy as np %matplotlib inline np.random.seed(42) x = np.random.normal(size=1000) plt.hist(x, density=True, bins=30) # density=False would make counts plt.ylabel(‘Probability’) plt.xlabel(‘Data’); Note, … Read more

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file. In [30]: x = np.linspace(0,6,31) In [31]: y = np.exp(-0.5*x) * np.sin(x) In [32]: plot(x, y, ‘bo-‘) Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>] In [33]: savefig(‘demo.png’, transparent=True) Result: Of course, that plot doesn’t demonstrate the transparency. Here’s a screenshot … Read more

Matplotlib – global legend and title aside subplots

Global title: In newer releases of matplotlib one can use Figure.suptitle() method of Figure: import matplotlib.pyplot as plt fig = plt.gcf() fig.suptitle(“Title centered above all subplots”, fontsize=14) Alternatively (based on @Steven C. Howell’s comment below (thank you!)), use the matplotlib.pyplot.suptitle() function: import matplotlib.pyplot as plt # plot stuff # … plt.suptitle(“Title centered above all subplots”, … Read more

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn’t display to the user, e.g. ‘Agg’: import matplotlib matplotlib.use(‘Agg’) import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig(‘/tmp/test.png’) EDIT: If you don’t want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are … Read more

Saving images in Python at a very high quality

If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image: plt.savefig(‘destination_path.eps’, format=”eps”) I have found that EPS files work best and the dpi parameter is what really makes them look good in … Read more