I try to do a basic igraph plotting in an IPython notebook:
fn = 'misrables.gml'
gr = igraph.Graph.Read_GML(fn)
igraph.plot(gr)
instead of seeing a graph I see this:
Out[7]: <igraph.drawing.Plot at 0x1120d6978>
How do I persuade IPython to actually show the graphics?
Some clarifications
Inline matplotlib works fine, so this is not the issue.
I have cairo installed:
import cairo
cairo.version
output: 1.10.0
Calling _repr_svg() on the plot object results in an error:
TypeError Traceback (most recent call last)
/Users/boris/Documents/workspace/communityAnalysis/src/utils.py in <module>()
----> 1 z = ig.plot(gr)._repr_svg_()
/usr/local/lib/python3.4/site-packages/igraph/drawing/__init__.py in _repr_svg_(self)
362 # No idea why this is needed but python crashes without
363 context.show_page()
--> 364 surface.finish()
365 # Return the raw SVG representation
366 return io.getvalue()
TypeError: string argument expected, got 'bytes'
Do you have the Cairo library and its Python bindings installed on your machine? The Plot object of igraph has a _repr_svg_ method that should be enough for IPython to show the plot, but _repr_svg_ uses Cairo behind the scenes to draw the graph into an SVG file, so if you don't have Cairo, _repr_svg_ probably throws an exception that IPython swallows, and then you get an ordinary repr() representation for the plot.
Update: based on the updated post, it turned out that the problem was that _repr_svg_ was not prepared for Python 3.x as it used a StringIO object where a BytesIO object would have been appropriate. Replacing io = StringIO() with io = BytesIO() at the beginning of the function and replacing return io.getvalue() with return io.getvalue().decode() at the end solves the problem. (from io import BytesIO is also needed at the top of igraph/drawing/__init__.py). A bug report has been filed on GitHub; the issue will be fixed in the next minor release.
Update: the issue is now fixed in the development version; see this commit for a patch.
Update for igraph 0.7.1 in python 3.7.4 and IPython 7.8.0
if you install the package with:
conda install python-igraph
Then you can simply use
igraph.plot(gr).show()
and in Ubuntu a .png will be displayed automatically in a separate window with ImageMagick
Related
The following code is supposed to display thumbnails of different images that are available in the \data directory. However, something is wrong with it.
from os import listdir
from os.path import isfile, join
mypath = "data/"
file_names = [mypath+f for f in listdir(mypath) if isfile(join(mypath, f))]
number_files = len(file_names)
fig = plt.figure(figsize = (40,50))
fig.subplots()
axes = []
for i ,file_name in enumerate(file_names):
dataset = pydicom.dcmread(file_name)
axes.append(fig.add_subplot(int(math.sqrt(number_files))+1 , int(math.sqrt(number_files))+1, i+1))
plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
plt.show()
I have the following error:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-73-3ed68a41a4d3> in <module>
10 dataset = pydicom.dcmread(file_name)
11 axes.append(fig.add_subplot(int(math.sqrt(number_files))+1 , int(math.sqrt(number_files))+1, i+1))
---> 12 plt.imshow(dataset.pixel_array, cmap=plt.cm.bone)
13 plt.show()
...
RuntimeError: The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. GDCM)
I've tried to do !conda install -c conda-forge gdcm -y but I've gotthe following error:
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes. Press CTRL-C to abort.
failed
UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:
Specifications:
- gdcm -> python[version='2.7.*|3.5.*|3.6.*|>=2.7,<2.8.0a0|>=3.6,<3.7.0a0|>=3.7,<3.8.0a0|3.4.*']
Your python: python=3.8
If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.
Any idea how to fix the error?
One alternative to GDCM that'll be available in the next released version of pydicom is pylibjpeg (disclosure: I'm a contributor to pydicom and author of pylibjpeg). You can use pylibjpeg with pydicom v2.0 simply by importing it before calling Dataset.pixel_array:
Installation
pip install pylibjpeg pylibjpeg-libjpeg
Usage
from pydicom import dcmread
import pylibjpeg
ds = dcmread('path/to/file.dcm')
arr = ds.pixel_array
If don't absolutely need python 3.8, you could try to create a new environment with a python 3.7 interpreter by using the following command line:
conda create -n myenv python=3.7
You could also try to install the dependency with pip from your existing environment.
I read two or three questions related to this problem but I haven't found any solution yet. I don't understand why I have this error.
I am using Python 3.7 and installed scipyusing the pip installer and it worked properly. For those who want to know, I was testing this program (from this website).
If I go in my Python libraries I have two folders as shown on the image below
Now if I go to the scipy folder, I actually have a _lib folder as shown in the image below. So I don't really understand why this error raised up. And I don't know nor understand what I should do.
I don't have any file called integrate inside this folder, so either I am wrong about where to find the module or I have an obsolete scipy version which seems to be hard to know if you just use the pip installer.
The full error code is:
Traceback (most recent call last):
File "C:\Users\YANN\Desktop\Numerical Method - Python\odeint_example.py", line 2, in <module>
from scipy.integrate import odeint
File "C:\Users\YANN\AppData\Roaming\Python\Python37\site-packages\scipy\__init__.py", line 110, in <module>
from scipy._lib._version import NumpyVersion as _NumpyVersion
ModuleNotFoundError: No module named 'scipy._lib'
Also in the file scipy._lib._version.py the docstring of the NumpyVersion class is shown after and I am wondering if it's ok to have a numpy version 1.15.2? I like my 1.15.2 numpy version...
class NumpyVersion():
"""Parse and compare numpy version strings.
Numpy has the following versioning scheme (numbers given are examples; they
can be >9) in principle):
- Released version: '1.8.0', '1.8.1', etc.
- Alpha: '1.8.0a1', '1.8.0a2', etc.
- Beta: '1.8.0b1', '1.8.0b2', etc.
- Release candidates: '1.8.0rc1', '1.8.0rc2', etc.
- Development versions: '1.8.0.dev-f1234afa' (git commit hash appended)
- Development versions after a1: '1.8.0a1.dev-f1234afa',
'1.8.0b2.dev-f1234afa',
'1.8.1rc1.dev-f1234afa', etc.
- Development versions (no git hash available): '1.8.0.dev-Unknown'
Comparing needs to be done against a valid version string or other
`NumpyVersion` instance.
Parameters
----------
vstring : str
Numpy version string (``np.__version__``).
Notes
-----
All dev versions of the same (pre-)release compare equal.
Examples
--------
>>> from scipy._lib._version import NumpyVersion
>>> if NumpyVersion(np.__version__) < '1.7.0':
... print('skip')
skip
>>> NumpyVersion('1.7') # raises ValueError, add ".0"
"""
Any tips will be very appreciated! :)
Previously ROS was installed in my system which requires opencv for its implementation and now I am using anaconda in which I need to use the opencv library once again. While writing python code import cv2 throws an error module not found.
Is there any way to use that opencv library which ROS installed in anaconda
Although I installed opencv once again using conda.
$conda install -c conda-forge opencv
however opencv-3.3 was installed using above command. Now my python code is showing different import error as shown below:
ImportError Traceback (most recent call last)
<ipython-input-9-6b49ad4d4ca5> in <module>()
1 from random import shuffle
2 import glob
----> 3 import cv2
4 shuffle_data = True # shuffle the addresses before saving
5 hdf5_path = 'dataset.hdf5' # address to where you want to save the hdf5 file
ImportError: /home/kamal/ros_catkin_ws/install_isolated/lib/python2.7/dist-packages/cv2.so: undefined symbol: PyCObject_Type
How can I particularly specify which opencv library to use. What env variables I need to change.
Any help will be appreciated.
uncommenting the line source /home/user/ros_catkin_ws/install_isolated/share/setup.bash in the .bashrc file dosen't help. You also need to remove the extrasys.path added by the ROS environment.
In a python console
import sys
print (sys.path)
you will see multiple paths related to ROS
then remove the unwanted part of the path by
sys.path.remove('unwanted_path')
This will solve the problem but now ROS will not work. To make it work you need to append the removed path again.
If someone has a better approach please answer.
I just want to draw a simple graph with Python 3 networkx & graphviz:
import networkx as nx
G = nx.complete_graph(3)
nx.draw_graphviz(G)
I'm using ubuntu14.04 and IPython3 and as usual I did pip3 install networkx and running the code gave me:
ImportError: pydot could not be loaded: http://code.google.com/p/pydot/
And I tried installing pydotplus and running the code:
/usr/local/lib/python3.4/dist-packages/networkx/drawing/nx_pydot.py in pydot_layout(G, prog, root, **kwds)
294
295 if isinstance(node,list):
--> 296 node=node[0]
297 pos=node.get_pos()[1:-1] # strip leading and trailing double quotes
298 if pos != None:
IndexError: list index out of range
and pydot2 also:
/usr/local/lib/python3.4/dist-packages/pydot.py in write(self, path, prog, format)
1893 prog = self.prog
1894
-> 1895 dot_fd = file(path, "w+b")
1896 if format == 'raw':
1897 data = self.to_string()
NameError: name 'file' is not defined
I spent quite some time searching and installing other pydots and pygraphviz combinations already but still no luck.
While this may be related:
pydot and graphviz error: Couldn't import dot_parser, loading of dot files will not be possible, that doesn't solve the problem in Python 3.
You can fix this by editing the line #292 from:
pydot_node = pydot.Node(make_str(n)).get_name().encode('utf-8')
to remove the encode at the end:
pydot_node = pydot.Node(make_str(n)).get_name() #.encode('utf-8')
I've reported this bug/fix here.
This seems to be the same issue as that the pydot you're using is a version incompatible with Python 3, which uses file(...). file(...) is removed in Python 3 already.
I noticed this issue and setup a Python 3 compatible version on PyPi.
For Linux systems for Python 3.x, try:
pip3 install pydot3
Or in general for Python 2.x, try:
pip install pydot3
Not a very great answer but it acts as a workaround.
First output the .dot file by
networkx.write_dot(G, 'graph.dot') using Python
and then do the appropriate graphviz output command like neato -T png graph.dot > graph.png on the command line.
I recently upgraded ipython to 2.0.0 and can't get inline plots to work. If I try
%pylab inline
plot([1,2],[1,2])
I get the following output:
Populating the interactive namespace from numpy and matplotlib
[<matplotlib.lines.Line2D at 0x10ffcf080>]
/usr/local/lib/python3.4/site-packages/IPython/core/formatters.py:239: FormatterWarning: Exception in image/png formatter: _image_module::readpng: png_create_read_struct failed
FormatterWarning,
<matplotlib.figure.Figure at 0x10e77ca58>
And in the console, I have the following error:
ERROR:tornado.application:Uncaught exception in /api/kernels/0a214dee-3143-4d34-89cb-9d65ce154fe6/shell
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/tornado/websocket.py", line 322, in wrapper
return callback(*args, **kwargs)
File "/usr/local/lib/python3.4/site-packages/IPython/html/services/kernels/handlers.py", line 122, in on_message
self.session.send(self.zmq_stream, msg)
File "/usr/local/lib/python3.4/site-packages/IPython/kernel/zmq/session.py", line 646, in send
stream.send_multipart(to_send, copy=copy)
AttributeError: 'NoneType' object has no attribute 'send_multipart'
Any idea what's going on here?
Edit: I'm on python 3.4.0, ipython 2.0.0, and matplotlib 1.3.1
As tcaswell mentioned, the easiest way of dealing with issues with dependencies of individual python modules is to test them in a virtual environment- effectively giving you a clean install. If nothing else, this helps the debugging process.
Make a virtual environment called myenv by running this in your
terminal: $ virtualenv myenv
Activate the environment by running from terminal: $ source
myenv/bin/activate.
Install ipython (the name of your virtualenvironment is now in
parentheses at your prompt: (myenv)$ pip install ipython notebook
Once you're done with the virtual environment, run $ deactivate or
close your terminal session.
There are a variety of good guides for virtual environments; I'd recommend starting here. If installing within a virtual environment doesn't fix things, there might be a bigger issue. Once you're done using the virtual environment, you can simply delete the folder created with its name (in this case myenv).
And finally, I'd recommend using %matplotlib inline over %pylab inline as discussed in this question.