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
Related
I'm using a library called GPy to fit a Gaussian process model and plot the output. The library has it's own plotting functionality, and returns a matplotlib figure.
I'd like to use this output in a holoviews element, as part of a dynamic map. This feels like it should be possible, but I can't find a good way to do it.
I had wondered about reading the matplotlib figure into a numpy image array and sending this to a holoviews Raster element - but the only way to do this seems to be saving the figure to a file, which does not seem a good option.
Great question! At the point where you define holoviews elements, they are still backend-agnostic. Matplotlib etc. only come into play when they are actually rendered. Hence no, you cannot take a matplotlib figure as such and pipe that into a holoviews element.
Hence you have two options:
Extract the data from the matplotlib figure in some way, or get hold of those data from GPy in some other way, and create a holoviews element from that, or
Use the code that generates the matplotlib figure in a panel (https://panel.pyviz.org) app.
Number 2 is closer to what you are probably imagining but without a minimal working example I cannot say much more.
I am new to NetworkX. Right now, I manage to connect all the nodes to this particular node. What I want to do next it to make it interactive e.g. able to make each of the node move by dragging using cursor. I know I have to make use of matplotlib, but I am not sure how to use it. Can anyone help me?
My codes are:
import matplotlib.pyplot as plt
import networkx as nx
import itertools
d = [name of nodes]
f = [number per nodes]
for i in d:
G.add_edge('"' + i + '"',b)
pos=nx.fruchterman_reingold_layout(G, k=0.5, iterations=5)
nx.draw_networkx_nodes(G,pos,node_size=130, node_color="white")
nx.draw_networkx_edges(G,pos, width=0.2,alpha=1,edge_color='black')
nx.draw_networkx_labels(G,pos,font_size=7,font_family='sans-serif')
for i,j in itertools.izip(d,f):
nx.draw_networkx_edge_labels(G,pos, {('"' + i + '"',b):j}, font_size=7, label_pos= 0.80)
plt.axis('off')
plt.show()
It seems hard to do with matplotlib (it is not really been designed for that). Networkx drawing module is pretty poor it mostly uses a custom scatter plot for nodes, etc.
I suggest another solution:
Export your graph to JSON or GEXF and use a Javascript graph drawing library to make your graph interactive such as: SigmaJs, or VivaGraphJs.
You find an example of a real graph created with NetworkX embedded on a webpage on my blog. Nodes are static in this example but clicking on a node highlights its neighbors.
Official examples for the proposed interactive graph drawing libraries:
List of examples using sigma.js.
Tutorial for VivaGraphJs.
Matplotlib was designed more for static graphs and charts.
However once the NetworkX graph is exported to GEXF format there is a tool which will allow you to select areas based on position or critera in order to move it around. The tool is called Gephi. You can play with the layout to get started or go as deep as data scientists like to get.
when I use inline plots in iPython (QtConsole), the first plot looks (more or less) fine, but then it gets weirder and weirder. When I plot something several times (so plot, see it displayed, plot again, see output etc.), it looks like it is being overlaid with the skewed previous picture. So after plotting a diagonal line (x=y) 4 times in a row I get something like this
If i right click and export it as svg everything looks good
(Exported PNG picture remains wrecked as the first one).
I guess the problem is similar to https://github.com/ipython/ipython/issues/1866, but I didn't got the upshot of the discussion (it got too technical and complicated for me to follow).
Is there any solution or work around for this issue?
I'm using
python 2.7
matplotlib 1.4.1
IPython 2.1.0
Here is a working example:
%matplotlib inline
% config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
a=range(10)
fig,ax=plt.subplots()
ax.plot(a,a)
ax.axis('off')
if you remove plt.axis('off') line, weird things happen only outside of the axis box.
P.S. Originally I encountered this problem in connection with drawing graphs with networkx. If I use draw from networkx this problem does not occur. If I use draw_networkx, same as described above happens. That might point to the core of the problem... I'm trying to figure out what line of code makes one work better than the other...
After tinkering around with the draw and draw_networkx functions from networkx module, I found the workaround which makes the difference between draw and draw_networkx in this case.
Adding fig.set_facecolor('w') overlays whatever is in the background, so the new plots are started with a white sheet (but not a blank one, I guess).
So new working example is:
%matplotlib inline
% config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
a=range(10)
fig,ax=plt.subplots()
fig.set_facecolor('w')
ax.plot(a,a)
ax.axis('off')
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')
I while ago, I was comparing the output of two functions using python and matplotlib. The result was as good as simple, since plotting with matplotlib is quite easy: I just plotted two arrays with different markers. Piece of cake.
Now I find myself with the same problem, but now I have a lot of pair of curves to compare. I initially tried plotting everything with different colors and markers. This did not satisfy me since the ranges of each curve are not quite the same. In addition to this, I quickly ran out of colors and markers that were sufficiently different to identify (RGBCMYK, after that, custom colors resemble any of the previous ones).
I also tried subplotting each pair of curves, obtaining a window with many plots. Too crowded.
I tried one window per plot, too many windows.
So I was just wondering if there is any existing widget or if you have any suggestion (or a different idea) to accomplish this:
I want to see a pair of curves and then select easily the next one, with a slidebar, button, mouse scroll, or any other widget or event. By changing curves, the previous one should disappear, the legend should change and its axis as well.
Well I managed to do it with an event handler for mouse clicks. I will change it for something more useful, but I post my solution anyway.
import matplotlib.pyplot as plt
figure = plt.figure()
# plotting
plt.plot([1,2,3],[10,20,30],'bo-')
plt.grid()
plt.legend()
def on_press(event):
print 'you pressed', event.button, event.xdata, event.ydata
event.canvas.figure.clear()
# select new curves to plot, in this example [1,2,3] [0,0,0]
event.canvas.figure.gca().plot([1,2,3],[0,0,0], 'ro-')
event.canvas.figure.gca().grid()
event.canvas.figure.gca().legend()
event.canvas.draw()
figure.canvas.mpl_connect('button_press_event', on_press)
Sounds like you want to embed matplotlib in an application. There are some resources available for that:
user interface examples
Embedding in WX
I really like using traits. If you follow the tutorial Writing a graphical application for scientific programming , you should be able to do what you want. The tutorial shows how to interact with a matplotlib graph using graphical user interface.