Showing posts with label Python (programming language). Show all posts
Showing posts with label Python (programming language). Show all posts

Wednesday, September 28, 2016

Python: Matplotlib: Tri-Surface plots Example

Noteworthy:

# "Repeat elements of an array."
numpy.repeat(a, repeats, axis=None)

# "Append values to the end of an array."
numpy.append(arr, values, axis=None)

# "Create a tri-surface plot."
Axes3D.plot_trisurf(*args, **kwargs)


Command:

$ cat Downloads/trisurf3d_demo.py


Result:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('dark_background')
n_angles = 36
n_radii = 8

# An array of radii
# Does not include radius r=0, this is to eliminate duplicate points
radii = np.linspace(0.125, 1.0, n_radii)

# An array of angles
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)

# Repeat all angles for each radius
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)

# Convert polar (radii, angles) coords to cartesian (x, y) coords
# (0, 0) is added here. There are no duplicate points in the (x, y) plane
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())

# Pringle surface
z = np.sin(-x*y)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)

plt.show()


Command:

$ python Downloads/trisurf3d_demo.py


Graphical output:



Tuesday, September 27, 2016

Python: Matplotlib: 3D Plot Example

Noteworthy:

# "Creates a new figure."
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs)

# "Renders into a FigureCanvas."
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)

# "Get the current Axes instance on the current figure matching the given keyword args, or create one."
matplotlib.pyplot.gca(**kwargs)

# "Return evenly spaced values within a given interval."
numpy.arange([start, ]stop, [step, ]dtype=None)

# "Return coordinate matrices from coordinate vectors."
numpy.meshgrid(*xi, **kwargs)

# "Return the positive square-root of an array, element-wise."
numpy.sqrt(x[, out]) = <ufunc 'sqrt'>

# "Trigonometric sine, element-wise."
numpy.sin(x[, out]) = <ufunc 'sin'>

# "Create a surface plot."
Axes3D.plot_surface(X, Y, Z, *args, **kwargs)


Command:

$ cat test3dplot.py


Result:

#!/usr/local/bin/python

from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('dark_background')
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)
plt.show()


Command:

$ python test3dplot.py

Graphical output:

Python: Matplotlib: Histogram Dark Background Example

Command:

$ cat testhistogram.py


Result:

#!/usr/local/bin/python

import matplotlib.pyplot as plt
plt.style.use('dark_background')

from numpy.random import normal,rand
x = normal(size=200)
plt.hist(x,bins=30)
plt.show()


Command:

$ python testhistogram.py


Graphical output:

Python: Matplotlib: Scatter Plot Dark Background Example

Command:

$ cat testscatterplot.py


Result:

#!/usr/local/bin/python

import matplotlib.pyplot as plt
plt.style.use('dark_background')

from numpy.random import rand
a = rand(100)
b = rand(100)
plt.scatter(a,b)
plt.show()


Command:

$ python testscatterplot.py


Graphical output:



Python: Matplotlib: Dark Background Example

Noteworthy:

# "Use matplotlib style settings from a style specification."
matplotlib.style.use(style)

# "Return the length (the number of items) of an object."
len(s)

# "An instance of RcParams for handling default matplotlib values."
matplotlib.rcParams

# "Set the x axis label of the current axis."
matplotlib.pyplot.xlabel(s, *args, **kwargs)

# "Set the y axis label of the current axis."
matplotlib.pyplot.ylabel(s, *args, **kwargs)

# "Set a title of the current axes."
matplotlib.pyplot.title(s, *args, **kwargs)


Command:

$ cat testdarkbackground.py


Result:

#!/usr/local/bin/python

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')

L = 6
x = np.linspace(0, L)
ncolors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, ncolors, endpoint=False)
for s in shift:
    plt.plot(x, np.sin(x + s), 'o-')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('title')

plt.show()


Command:

$ python testdarkbackground.py


Graphical output:

Python: Matplotlib: Scatter Plot Example

Noteworthy:

# "Random values in a given shape."
numpy.random.rand(d0, d1, ..., dn)

# "Make a scatter plot of x vs y, where x and y are sequence like objects of the same length."
matplotlib.pyplot.scatter(x, y, s=20, c=None, marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)


Command:

$ cat testscatterplot.py


Result:

#!/usr/local/bin/python

import matplotlib.pyplot as plt
from numpy.random import rand
a = rand(100)
b = rand(100)
plt.scatter(a,b)
plt.show()


Command:

$ python testscatterplot.py


Graphical output:

Python: Matplotlib: Histogram Example

Noteworthy:

# "Draw random samples from a normal (Gaussian) distribution."
# 正規分布(ガウス分布)からランダムにサンプルして線を描く。
numpy.random.normal(loc=0.0, scale=1.0, size=None)

# "Plot a histogram"
# ヒストグラムをプロット(描写)する。
matplotlib.pyplot.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, hold=None, data=None, **kwargs)


Command:

$ cat testhistogram.py


Result:

#!/usr/local/bin/python

import matplotlib.pyplot as plt
from numpy.random import normal,rand
x = normal(size=200)
plt.hist(x,bins=30)
plt.show()


Command:

$ python testhistogram.py


Graphical output:




Python: Matplotlib: Line Plot Example

Noteworthy:

# "Return evenly spaced numbers over a specified interval."
# 等間隔に並べた数字を返す。
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

# "Calculate the exponential of all elements in the input array."
# 指数の計算
numpy.exp(x[, out]) = <ufunc 'exp'>

# "Display a figure."
# フィギュアを表示する。
matplotlib.pyplot.show(*args, **kw)


Command:

$ cat testlineplot.py


Result:

#!/usr/local/bin/python

import matplotlib.pyplot as plt
import numpy as np
a = np.linspace(0,10,100)
b = np.exp(-a)
plt.plot(a,b)
plt.show()


Graphical output:

macOS Sierra: Python: Plot and Save Image File Using Matplotlib

Noteworthy:

# Using AGG - The Anti-Grain Geometry (Agg) rendering engine
import matplotlib
matplotlib.use('Agg')

# Plot lines and/or markers to the Axes.
# args is a variable length argument, allowing for multiple x, y pairs with an optional format string.
import matplotlib.pyplot as plt
plt.plot(*args)

# Save the current figure
import matplotlib.pyplot as plt
plt.savefig(FILENAME)


Command:

$ cat testplotandsavefig.py


Result:

#!/usr/local/bin/python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')


Command:

$ chmod +x testplotandsavefig.py
$ ./testplotandsavefig.py


Result:

Traceback (most recent call last):
  File "./testplotandsavefig.py", line 2, in <module>
    import matplotlib
ImportError: No module named matplotlib


Command (Installing matplotlib):

$ brew install matplotlib


Result:

==> Auto-updated Homebrew!
Updated Homebrew from 6e57355 to e4ed309.
Updated 2 taps (homebrew/core, homebrew/science).
==> New Formulae
gofabric8                  httpdiff                   linkerd                
==> Updated Formulae
airspy                                   openssl ✔                            
antigen                                  openssl@1.1                          
argyll-cms                               pgrouting                            
cgal                                     postgis                              
chaiscript                               protobuf-swift                      
consul-template                          purescript                          
fzf                                      sfcgal                              
homebrew/science/exabayes                spdylay                              
homebrew/science/nextflow                storm                                
homebrew/science/sortmerna               the_silver_searcher                  
homebrew/science/vtk                     varnish                              
jetty                                    vim ✔                                
jsoncpp                                  wellington                          
launch                                   wolfssl                              
legit                                    yle-dl                              
libpointing                              you-get                              
mobile-shell                             zplug                                
nghttp2                              
==> Deleted Formulae
aeskeyfind

==> Installing matplotlib from homebrew/python
==> Downloading https://pypi.python.org/packages/source/m/matplotlib/matplotlib-
######################################################################## 100.0%
==> Downloading https://pypi.python.org/packages/source/s/setuptools/setuptools-
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/C/Cycler/cycler-0.9.0.ta
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/f/funcsigs/funcsigs-0.4.
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/n/nose/nose-1.3.7.tar.gz
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/m/mock/mock-1.3.0.tar.gz
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/p/pbr/pbr-1.8.1.tar.gz
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/p/pyparsing/pyparsing-2.
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/p/python-dateutil/python
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/p/pytz/pytz-2015.7.tar.b
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Downloading https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz
######################################################################## 100.0%
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> python -c import setuptools... --no-user-cfg install --prefix=/usr/local/Cel
==> Caveats
If you want to use the `wxagg` backend, do `brew install wxpython`.
This can be done even after the matplotlib install.
==> Summary
🍺  /usr/local/Cellar/matplotlib/1.5.1: 3,513 files, 76.5M, built in 1 minute 15 seconds


Command:

$ ./testplotandsavefig.py


Result (Error):

Traceback (most recent call last):
  File "./testplotandsavefig.py", line 2, in <module>
    import matplotlib
  File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 1131, in <module>
    rcParams = rc_params()
  File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 975, in rc_params
    return rc_params_from_file(fname, fail_on_error)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 1100, in rc_params_from_file
    config_from_file = _rc_params_in_file(fname, fail_on_error)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 1018, in _rc_params_in_file
    with _open_file_or_url(fname) as fd:
  File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/usr/local/lib/python2.7/site-packages/matplotlib/__init__.py", line 1000, in _open_file_or_url
    encoding = locale.getdefaultlocale()[1]
  File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 545, in getdefaultlocale
    return _parse_localename(localename)
  File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 477, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8


Command:

$ locale


Result:

LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=


Command (Fixing locale):

$ LC_CTYPE="C"
$ locale


Result:

LANG=
LC_COLLATE="C"
LC_CTYPE="C"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=


Command:

$ ./testplotandsavefig.py


Result:

/usr/local/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')


Command:

$ ls myfig*


Result:

myfig.png


Command (Opening image file):

$ open myfig.png





Tuesday, July 5, 2016

Friday, March 25, 2016

Python: Converting Percent-encoded String to Multibyte String

Command:

$ python -c "import urllib, sys; print urllib.unquote(sys.argv[1])" %E7%B9%94%E7%94%B0%E4%BF%A1%E9%95%B7

Output:

織田信長

Python: Percent-encode Multibyte String

Percent-encode multibyte string:

$ python -c "import urllib, sys; print urllib.quote(sys.argv[1])" 織田信長

Output:

%E7%B9%94%E7%94%B0%E4%BF%A1%E9%95%B7

Monday, March 21, 2016

pip: Installing pip (Package Manager for Python) on OS X Using easy_install

Command:

$ sudo easy_install pip

Result:

Password:
Searching for pip
Reading https://pypi.python.org/simple/pip/
Best match: pip 8.1.1
Downloading https://pypi.python.org/packages/source/p/pip/pip-8.1.1.tar.gz#md5=6b86f11841e89c8241d689956ba99ed7
Processing pip-8.1.1.tar.gz
Writing /tmp/easy_install-1rbqCh/pip-8.1.1/setup.cfg
Running pip-8.1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-1rbqCh/pip-8.1.1/egg-dist-tmp-OTECPf
warning: no previously-included files found matching '.coveragerc'
warning: no previously-included files found matching '.mailmap'
warning: no previously-included files found matching '.travis.yml'
warning: no previously-included files found matching '.landscape.yml'
warning: no previously-included files found matching 'pip/_vendor/Makefile'
warning: no previously-included files found matching 'tox.ini'
warning: no previously-included files found matching 'dev-requirements.txt'
warning: no previously-included files found matching 'appveyor.yml'
no previously-included directories found matching '.github'
no previously-included directories found matching '.travis'
no previously-included directories found matching 'docs/_build'
no previously-included directories found matching 'contrib'
no previously-included directories found matching 'tasks'
no previously-included directories found matching 'tests'
Adding pip 8.1.1 to easy-install.pth file
Installing pip script to /usr/local/bin
Installing pip2.7 script to /usr/local/bin
Installing pip2 script to /usr/local/bin

Installed /Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg
Processing dependencies for pip

Finished processing dependencies for pip

Friday, February 5, 2016

Python: Print Hello

$ python -c 'print "hello"'

Version of Python

$ python --version
Python 2.7.10