Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I duplicate this simple matlab plot functionality with mathplotlib?

Tags:

python

matlab

Here is a simple matlab script to read a csv file, and generate a plot (with which I can zoom in with the mouse as I desire). I would like to see an example of how this is done in python and mathplotlib.

data = csvread('foo.csv');    % read csv data into vector 'data'
figure;                       % create figure
plot (data, 'b');             % plot the data in blue

In general, the examples in mathplotlib tutorials I've seen will create a static graph, but it's not interactively "zoomable". Would any python expert care to share an equivalent?

Thanks

like image 552
loneRanger Avatar asked Dec 08 '10 20:12

loneRanger


People also ask

Is matplotlib and MATLAB similar?

Matplotlib is a library for making 2D plots of arrays in Python. Although it has its origins in emulating the MATLAB graphics commands, it is independent of MATLAB, and can be used in a Pythonic, object-oriented way.

What's the correct way to import the plot command in matplotlib?

In the command line, check for matplotlib by running the following command: python -c "import matplotlib"


2 Answers

import matplotlib.pyplot as plt
import numpy as np

arr=np.genfromtxt('foo.csv',delimiter=',')
plt.plot(arr[:,0],arr[:,1],'b-')
plt.show()

on this data (foo.csv):

1,2
2,4
3,9

produces

alt text

When you setup the matplotlibrc, one of the key parameters you need to set is the backend. Which backend you choose depends on your OS and installation. For any typical OS there should be a backend that allows you to pan and zoom the plot interactively. (GtkAgg works on Ubuntu). The buttons highlighted in red allow you to pan and zoom, respectively.

like image 132
unutbu Avatar answered Sep 21 '22 23:09

unutbu


Since you're familiar with Matlab, I'd suggest using the pylab interface to matplotlib - it mostly mimics Matlab's plotting. As unutbu says, the zoomability of the plot is determined by the backend you use, a separate issue.

from pylab import *
data = genfromtxt("file.csv")
plot(data, 'b')
like image 41
Thomas Avatar answered Sep 21 '22 23:09

Thomas