EzDevInfo.com

matplotlib

matplotlib: plotting with Python matplotlib: python plotting — Matplotlib 1.4.3 documentation

How do I set figure title and axes labels font size in matplotlib?

I am creating a figure in matplotlib like this:

from matplotlib import pyplot as plt    

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')

I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?


Source: (StackOverflow)

Matplotlib: How to put individual tags for a scatter plot

I am trying to do a scatter plot in Matplotlib and I couldn't find a way to add tags to the points. For example:

    scatter1=plt.scatter(data1["x"], data1["y"], marker="o",
                        c="blue",
                        facecolors="white",
                        edgecolors="blue")

I want for the points in "y" to have labels as "point 1", "point 2", etc. I couldn't figure it out.

Thanks!


Source: (StackOverflow)

Advertisements

matplotlib Legend Markers Only Once

I often plot a point on a matplotlib plot with:

x = 10
y = 100
plot(x, y, "k*", label="Global Optimum")
legend()

However, this causes the legend to put a star in the legend twice, such that it looks like:

* * Global Optimum

when I really want it to look like:

 *  Global Optimum

How do I do this?


Source: (StackOverflow)

Changing the "tick frequency" on x or y axis in matplotlib?

I am trying to fix how python plots my data.

Say

x = [0,5,9,10,15]

and

y = [0,1,2,3,4]

Then I would do:

matplotlib.pyplot.plot(x,y)
matplotlib.pyplot.show()

and the x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?


Source: (StackOverflow)

Generating matplotlib graphs without a running X server [duplicate]

This question already has an answer here:

Matplotlib seems to require the $DISPLAY environment variable which means a running X server.
Some web hosting services do not allow a running X server session.
Is there a way to generate graphs using matplotlib without a running X server?

[username@hostname ~]$ python2.6
Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/username/lib/python2.6/matplotlib-1.0.1-py2.6-linux-i686.egg/matplotlib/pyplot.py", line 270, in figure
    **kwargs)
  File "/home/username/lib/python2.6/matplotlib-1.0.1-py2.6-linux-i686.egg/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/local/lib/python2.6/lib-tk/Tkinter.py", line 1643, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
>>>

Source: (StackOverflow)

Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype'

When performing pip install -r requirements.txt, I get the following error during the stage where it is installing matplotlib:

REQUIRED DEPENDENCIES AND EXTENSIONS
                 numpy: yes [not found. pip may install it below.]
              dateutil: yes [dateutil was not found. It is required for date
                        axis support. pip/easy_install may attempt to
                        install it after matplotlib.]
               tornado: yes [tornado was not found. It is required for the
                        WebAgg backend. pip/easy_install may attempt to
                        install it after matplotlib.]
             pyparsing: yes [pyparsing was not found. It is required for
                        mathtext support. pip/easy_install may attempt to
                        install it after matplotlib.]
                 pycxx: yes [Couldn't import.  Using local copy.]
                libagg: yes [pkg-config information for 'libagg' could not
                        be found. Using local copy.]
              freetype: no  [pkg-config information for 'freetype2' could
                        not be found.]

...

The following required packages can not be built:

                    * freetype

Shouldn't pip install -r requirements.txt also install freetype? How should freetype be installed in Ubuntu 12.04 so it works with matplotlib?


Source: (StackOverflow)

Pip install Matplotlib error with virtualenv

I am trying to install matplotlib in a new virtualenv.

When I do:

pip install matplotlib

or

pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz

I get this error:

building 'matplotlib._png' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC -  DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I. -I/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/numpy/core/include -I. -I/usr/include/python2.7 -c src/_png.cpp -o build/temp.linux-x86_64-2.7/src/_png.o

src/_png.cpp:10:20: fatal error: png.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

Anyone have an idea what is going on?

Any help much appreciated.


Source: (StackOverflow)

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

I'm familiar with the following questions:

Matplotlib savefig with a legend outside the plot

How to put the legend out of the plot

It seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits.

Shrinking the axes, however, is not an ideal solution because it makes the data smaller making it actually more difficult to interpret; particularly when its complex and there are lots of things going on ... hence needing a large legend

The example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points.

http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-plots

What I would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legend.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
ax.grid('on')

Notice how the final label 'Inverse tan' is actually outside the figure box (and looks badly cutoff - not publication quality!) enter image description here

Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a little confused why this is so difficult in python... Is there a historical reason? Is Matlab equally poor on this matter?

I have the (only slightly) longer version of this code on pastebin http://pastebin.com/grVjc007


Source: (StackOverflow)

PyPlot reverse Y-Axis

I have a scatter plot graph with a bunch of random x,y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0.

points = [(10,5), (5,11), (24,13), (7,8)]    
x_arr = []
y_arr = []
for x,y in points:
    x_arr.append(x)
    y_arr.append(y)
plt.scatter(x_arr,y_arr)

Source: (StackOverflow)

Improve subplot size/spacing with many subplots in matplotlib

Very similar to this question but with the difference that my figure can be as large as it needs to be.

I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using figsave and viewed on a webpage, so I don't care how tall the final image is as long as the subplots are spaced so they don't overlap.

No matter how big I allow the figure to be, the subplots always seem to overlap.

My code currently looks like

import matplotlib.pyplot as plt
import my_other_module

titles, x_lists, y_lists = my_other_module.get_data()

fig = plt.figure(figsize=(10,60))
for i, y_list in enumerate(y_lists):
    plt.subplot(len(titles), 1, i)
    plt.xlabel("Some X label")
    plt.ylabel("Some Y label")
    plt.title(titles[i])
    plt.plot(x_lists[i],y_list)
fig.savefig('out.png', dpi=100)

Source: (StackOverflow)

How to make IPython notebook matplotlib plot inline

I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.

I cannot get matplotlib graphics to show up inline.

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

Instead of inline graphics, I get this:

<matplotlib.figure.Figure at 0x110b9c450>

And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.


Source: (StackOverflow)

What is the difference between pylab and pyplot? [duplicate]

This question already has an answer here:

What is the difference between matplotlib.pyplot and matplotlib.pylab?

Which is preferred for what usage?

I am a little confused, because it seems like independent from which I import, I can do the same things. What am I missing?


Source: (StackOverflow)

Generate a heatmap in MatPlotLib using a scatter data set

I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap.

I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate the image.

Is there a method that converts a bunch of x,y, all different, to a heatmap (where zones with higher frequency of x,y would be "warmer")?


Source: (StackOverflow)

How do I tell matplotlib that I am done with a plot?

The following code plots to two PostScript (.ps) files, but the second one contains both lines.

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

plt.subplot(111)
x = [1,10]
y = [30, 1000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("first.ps")


plt.subplot(111)
x = [10,100]
y = [10, 10000]
plt.loglog(x, y, basex=10, basey=10, ls="-")
plt.savefig("second.ps")

How can I tell matplotlib to start afresh for the second plot?


Source: (StackOverflow)

Confusion between numpy, scipy, matplotlib and pylab

Numpy, scipy, matplotlib, and pylab are common terms among they who use python for scientific computation.

I just learn a bit about pylab, and I got a lot of confusion. Whenever I want to import numpy, I can always do:

import numpy as np

I just consider, that once I do

from pylab import *

The numpy will be imported as well (with np alias). So basically the second one do more things compared to the first one.

There are few things I want to ask.

  1. Is it right that pylab is just a wrapper for numpy, scipy and matplotlib?
  2. As np is the numpy alias in pylab, what is the scipy and matplotlib alias in pylab? (as far as I know, plt is alias of matplotlib.pyplot, but I don't know the alias for the matplotlib itself)

Thanks in advance.


Source: (StackOverflow)