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
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
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.
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')
Related
using Python I would like to plot a curve for the function y=cosh(x)*cos(5x) in my Jupyter Notebook.
In other words:
(cosine hyperbolicus of x) times (cosine of 5x)
How do I do this?
What do I need to import?
Thank you very much in advance.
Greetings
Specify the range of values for x that you need.
You can use Seaborn on top of Matplotlib to make it prettier, but this is optional:
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-5,5,0.1) # start,stop,step
y= (np.cosh(x))*(np.cos(5*x) )
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above)
sns.set(style="darkgrid")
plt.plot(x,y)
plt.show()
You will need to import a plotting library and a maths library. The most commonly used plotting library is matplotlib, and for maths it's numpy. For plotting, bokeh is a an alternative to matplotlib, which I think is great because graphs are interactive by default. The disadvantage is that because it's not as widely used as matplotlib, you're less likely to find help on it in terms of StackOverflow answers and tutorials.
Anyway, to the code:
# Import the necessary packages and modules
import matplotlib.pyplot as plt
import numpy as np
# Set your x-range and calculate y
xmin = -2.5
xmax = 2.5
numPoints = 100
x = np.linspace(xmin, xmax, numPoints)
y = np.cosh(x)*np.cos(5*x)
# Plot -- it really can be this simple [1]
plt.plot(x,y)
Both of the graphing libraries above give you flexible options on where to place the axes, legends, titles, and so on. I recommend searching for beginner's tutorials on them to learn this stuff in depth.
[1] There are two ways to plot in matplotlib. What is shown here is the MATLAB-like interface. The other method is to use the object-based interface, which takes a bit more of getting used to, and requires a bit more boilerplate code, but that's what you will end up using once you demand more control over the appearance of your plots.
I recommend starting with the MATLAB-like commands first. The documentation has a good beginner's tutorial: https://matplotlib.org/stable/tutorials/introductory/pyplot.html
I'm trying to visualize frequency of imported from reports items in array using Python. I'm new to drawing graphs, so how to do it, using any module?
To draw graphs in python you need to do the following,
import matplotlib as plt
plt.plot(array_1,array_2)
plt.show()
I highly recommend checking out this Matplotlib Docs
It's not clear to me why plotting is done like this:
import pandas as pd
import matplotlib.pyplot as plt
df.boxplot(column='initial_cost', by='Borough', rot=90)
plt.show()
How is the dataframe tied to plt.show()? I've done a few web searches and even took a look at the documentation(!) but couldn't find anything addressing this specifically.
I would expect something more like:
boxplot = df.boxplot(column='initial_cost', by='Borough', rot=90)
plt.show(boxplot)
Or even something like this:
boxplot = df.boxplot(column='initial_cost', by='Borough', rot=90)
boxplot.plt.show()
Matplotlib provides a MATLAB-like state-machine, the pyplot module, that takes care under the hood of instantiating and managing all the objects you need to draw a plot.
Pandas hooks into that in the same fashion. When you call it takes care of loading pyplot and creating a matplotlib Figure, Axes, several Line2D objects and everything that makes a boxplot.
When you call plt.show() it will track all the figures you created with the state-machine API, create a GUI with those figures and take care of displaying it.
If you need more control, you can of course do it all yourself with the object-oriented API. Create a figure, axes, manually draw the canvas, it's all there if needed.
As far as I've seen the common practice is a mix of both: hook into the object-oriented API when needed but still let pyplot take care of displaying or saving everything to a file.
i have a python interface using wxpython which allows the user to fill in a matrix (0/1) and then graphs it for them. The program creates a numpy matrix, then makes a networkx graph out of that matrix, and then uses matplotlib.pylab to display the graph.
numpy is a must, because the program also does other things like get the transitive, reflexive, and symmetric closures... as for networkx i can use something else if u recommend something else better for graphing matrices, and as for matplotlib, i hate it, please if u know of any other way to display a graph please advice.
matplotlib is the source of my problem, when the users clicks the graph button, my programs reads the matrix, makes a graphs and matplotlib displays it in a new window (by default). Now if the users goes back to the original window and graphs a different matrix without first closing the matplotlib window, the program crashes.
also the way the relationship "arrows" are drawn is, in my opinion, unattractive.
i need a better way to graph my matrix, or at the very least as a way to force close the myplotlib window, i tried plt.close() but that didnt work, the window would remain open, and both windows will say (Not Responding) and i have to end process.
this is the part of the code in question:
import numpy as np
import networkx as nx
import matplotlib.pylab as plt
...
...
...
def graph(values)
plt.close() #with or without this it does not work
matrix = np.matrix(values)
graph = nx.DiGraph(matrix)
nx.draw(graph)
plt.show()
return
It seems to me like your main complaint is in the way that wx handles the matplotlib windows. It is possible to embed the Matplotlib figure in your wx window. Here's an example:
http://wiki.scipy.org/Matplotlib_figure_in_a_wx_panel (updated)
It gets a bit complicated. Basically, you should copy the code and replace the "DemoPlotPanel.draw()" method. You'll need to modify your code to specify the axis to draw on. It's buried in the networkx documentation here:
http://networkx.lanl.gov/reference/drawing.html
I am just using an example of the Networkx documentation:
try:
import matplotlib.pyplot as plt
except:
raise
import networkx as nx
G=nx.star_graph(20)
pos=nx.spring_layout(G)
nx.draw(G,pos)
plt.show() # display
So your plt.close() statement at the start does not make sense, you should remove it.You should also calculate the coordinates for your nodes, the sentence pos=nx.spring_layout(G) does this. You call a specific layout algorithm and supply your graph G, you get a dictionary in return with for each node the x and y coordinates.
Have a close look at the examples at: http://networkx.lanl.gov/gallery.html
Can we control where Matplotlib places figures on the screen?
I want to generate four figures (in four separate windows) that do not overlap.
From IPython you can do the following:
figure()
get_current_fig_manager().window.wm_geometry("400x600+20+40")
Or equivalently in a Python script:
import pylab as pl
pl.figure()
pl.get_current_fig_manager().window.wm_geometry("400x600+20+40")
pl.show()
Note that this assumes you're using the TkAgg backend.
It is also possible to use the IPython interface with the Qt backend to achieve a similar result:
import matplotlib
import pylab as pl
f1 = pl.figure()
f_manager = pl.get_current_fig_manager()
f_manager.window.move(600, 600)
pl.show()
With f_manager you basically have a PyQt4 object that allows you to modify the window properties as you like.
Not using show() and Matplotlib alone. The simplest solution may be to use savefig(..) and use your favorite OS image viewer. If you need interactivity with the plots, Matplotlib offers backends.
The easiest way I know to do this is to make the window for the figure in your preferred GUI application, and then put the matplotlib figure into this window. There are a bunch of examples of how to do this embedding using different GUI frameworks here.
The code samples can look a bit complicated, but it's mostly boilerplate where you'll only need to modify a few lines.