Create a Python3 environment with pyenv on Mac and display a NetworkX graph

Preamble

I tried to display the network diagram using NetworkX of Python in the Wikipedia link data that I imported earlier, but it took time to build the environment. So leave the steps. By the way, I learned about NetworkX at the Python Beginners' Gathering that came out last week.

Homebrew installation

Excuse me from a very rudimentary point, but check with the brew command whether the package management tool Homebrew for Mac is installed.

brew --version

If you haven't installed it yet, install Homebrew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
/master/install)"

-Japanese page of Homebrew official website

If it was installed, update it to the latest version.

brew update

pyenv-Create virtualenv environment

What is pyenv-virtualenv?

The Mac has 2 Pythons from the beginning, but I want to keep this environment and make the project to be 3 3s, so I can automatically switch between multiple versions of Python environment [pyenv-virtualenv]( (https://github.com/yyuu/pyenv-virtualenv) is installed.

pyenv is a Python multi-environment switching tool (Simple Python version management) virtualenv is the official Python Virtual Python Environment builder.

It seems that pyenv-virtualenv is a library that uses virtualenv from pyenv. Anyway, with pyenv-virtualenv, you will be able to automatically switch any directory between Python 2 and 3.

Qiita already has a lot of explanations on building an environment for pyenv and pyenv-virtualenv.

-Pyenv + virtualenv on Mac -Building an environment with pyenv and virtualenv -Building Python 3.x environment with Pyenv (CentOS, Ubuntu)

Install pyenv-virtualenv

brew install pyenv-virtualenv

By the way, this installation will also automatically install the dependent pyenv.

$ brew install pyenv-virtualenv
==> Installing dependencies for pyenv-virtualenv: autoconf, pkg-config, openssl, readline, pyenv

pyenv-virtualenv settings

Set environment variables after installation

~/.bash_profile


export PYENV_ROOT=$HOME/.pyenv
export PATH=$PYENV_ROOT/bin:$PATH
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Reflecting changes in environment variables

source ~/.bash_profile

Let's display the installable version with pyenv.

pyenv install --list

Find the latest version of Python 3 from the list and install it.

pyenv install 3.5.1

Python will be downloaded and installed from www.python.org like this.

$ pyenv install 3.5.1
Downloading Python-3.5.1.tgz...
-> https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
Installing Python-3.5.1...

When finished, reflect the changes in the environment variables again.

source ~/.bash_profile

Go to your working directory and have Python 3.5.1 running in that directory.

cd [Any working directory for Python 3]
pyenv local 3.5.1

When you're done, make sure the environment switches.

$ cd ~
$ python --version
Python 2.7.10

$ cd [Any working directory for Python 3]
$ python --version
Python 3.5.1

pip update

I'm about to install NetworkX, which uses pip, Python's package management system. In Python3, the pip command is attached by default, but if it is the default, it seems to be an old version, so I will update it.

cd [Any working directory for Python 3]
pip install --upgrade pip
$ pip list
Omission
pip (7.1.2)
Omission

$ pip install --upgrade pip

$ pip list
Omission
pip (8.0.2)
Omission

NetworkX installation

NetworkX is a library for dealing with complex networks in Python.

NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.

cd [Any working directory for Python 3]
pip install networkx

After the installation, it seems that the networkx module is placed under .pyenv / versions / 3.5.1.

$ ls ~/.pyenv/versions/3.5.1/lib/python3.5/site-packages/networkx
__init__.py		classes			drawing			generators		relabel.py		tests
__pycache__		convert.py		exception.py		linalg			release.py		utils
algorithms		convert_matrix.py	external		readwrite		testing			version.py

$ ls ~/.pyenv/versions/3.5.1/share/doc/networkx-1.11/examples
3d_drawing	advanced	algorithms	basic		drawing		graph		multigraph	pygraphviz

Try console display on NetworkX

As a test, let's run the First Sample on the NetrowkX site.

networkx-sample.py


import networkx as nx

G=nx.Graph()
G.add_node("spam")
G.add_edge(1,2)

print(G.nodes())
print(G.edges())

Create a networkx-sample.py script in the environment set in Python3 and execute it.

$ cd [Any working directory for Python 3]
$ python networkx-sample.py 
['spam', 2, 1]
[(2, 1)]

The nodes and edges of the network are displayed in the console.

Install matplotlib

Next, I will try to find and execute the Sample that graphically displays the network from the official website. , It seems that the matplotlib library is required for graph display.

Also install with the pip command.

pip install matplotlib

If you run the sample as it is, an error will occur. Is the error message pointing to this page?

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. 
See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. 
If you are Working with Matplotlib in a virtual enviroment see 'Working with Matplotlib in Virtual environments' in the Matplotlib FAQ

(The error message has a long line, so it has a line break.)

I did not solve it even if I did it as written, so I will search for a solution from Qiita. Reference: Cannot import matplotlib etc. in VirtualEnv environment

Create a new matplotlibrc file

~/.matplotlib/matplotlibrc

One line description in matplotlibrc

backend : TkAgg

Try to display the network diagram with NetworkX

Create a Python script by copying the sample Random Geometric Graph from the official website.

RandomGeometricGraph.py


import networkx as nx
import matplotlib.pyplot as plt

G=nx.random_geometric_graph(200,0.125)
# position is stored as node attribute data for random_geometric_graph
pos=nx.get_node_attributes(G,'pos')

# find node near center (0.5,0.5)
dmin=1
ncenter=0
for n in pos:
    x,y=pos[n]
    d=(x-0.5)**2+(y-0.5)**2
    if d<dmin:
        ncenter=n
        dmin=d

# color by path length from node near center
p=nx.single_source_shortest_path_length(G,ncenter)

plt.figure(figsize=(8,8))
nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4)
nx.draw_networkx_nodes(G,pos,nodelist=p.keys(),
                       node_size=80,
                       node_color=[float(v) for v in p.values()],
                       cmap=plt.cm.Reds_r)

plt.xlim(-0.05,1.05)
plt.ylim(-0.05,1.05)
plt.axis('off')
plt.savefig('random_geometric_graph.png')
plt.show()

It didn't work in Python3 as it was, so I changed one line.

original

node_color=p.values()

I changed it like this. I think it's the difference between 2 and 3 series, but it may be due to the version of matplotlib.

node_color=[float(v) for v in p.values()]

Run sample

When I ran the sample, somehow a network diagram was displayed and a random_geometric_graph.png file was created.

python RandomGeometricGraph.py

スクリーンショット 2016-02-01 14.38.15.png

Recommended Posts

Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Create a Python environment on Mac (2017/4)
Create a Python (pyenv / virtualenv) development environment on Mac (Homebrew)
Create a python environment on your Mac
Build a Python environment on your Mac with Anaconda and PyCharm
Build a Python environment on your Mac using pyenv
Create a decent shell and python environment on Windows
Building a Python environment on Mac
Create a virtual environment with Python!
Create a python environment on centos
Building a Python environment on a Mac and using Jupyter lab
Create a virtual environment for python on mac [Very easy]
VScode environment construction (on Mac) & graph display in Python (@browser)
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Steps to quickly create a deep learning environment on Mac with TensorFlow and OpenCV
[Pyenv] Building a python environment with ubuntu 16.04
[Python] Create a virtual environment with Anaconda
A memo with Python2.7 and Python3 on CentOS
Notes on building Python and pyenv on Mac
Build Python environment with Anaconda on Mac
Build a python virtual environment with pyenv
Build a 64-bit Python 2.7 environment with TDM-GCC and MinGW-w64 on Windows 7
Create a C ++ and Python execution environment with WSL2 + Docker + VSCode
Create a simple Python development environment with VS Code and Docker
Python3 TensorFlow environment construction (Mac and pyenv virtualenv)
Build python environment with pyenv on EC2 (ubuntu)
Building a python environment with virtualenv and direnv
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
Build a python environment with ansible on centos6
Build a Python environment on Mac (Mountain Lion)
Create a virtual environment with conda in Python
Create a python3 build environment with Sublime Text3
Steps to create a Python virtual environment with VS Code on Windows
Try to build python and anaconda environment on Mac (by pyenv, conda)
Build a virtual environment with pyenv and venv
[Venv] Create a python virtual environment on Ubuntu
Put Python 2.7.x on Mac OSX 10.15.5 with pyenv
Notes on setting pyenv and python environment using Homebrew on Mac OS Marvericks
Create a Mac app using py2app and Python3! !!
Remove old pyenv environment on Mac and update
Create a Python execution environment on IBM i
Create a Python3.4 + Nginx + uWSGI + Flask Web application execution environment with haste using pyenv on Ubuntu 12.04
Create a Python virtual development environment on Windows
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Trial and error]
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
Install Python3 on Mac and build environment [Definitive Edition]
Build a python virtual environment with virtualenv and virtualenvwrapper
Install selenium on Mac and try it with python
Create a virtual environment with Anaconda installed via Pyenv
Build a machine learning Python environment on Mac OS
Create a comfortable Python 3 (Anaconda) development environment on windows
Create a python development environment with vagrant + ansible + fabric
I made a Python3 environment on Ubuntu with direnv.
Build a Python development environment on Mac OS X
Build a python virtual environment with virtualenv and virtualenvwrapper
Build a Python development environment using pyenv on MacOS
Install Python environment on local PC (pyenv, venv on Mac)
Create a Python development environment on OS X Lion
Build a numerical calculation environment with pyenv and miniconda3
Draw a graph with NetworkX
python with pyenv and venv