Use matplotlib on Ubuntu 12 & Python

I want to draw a graph! The first two things that came to my mind were R and Python. I've used R in the past, so this time I tried using Python. In the case of Python, it was written that it seems that graphs can be drawn by using matplotlib, so first I tried to see if the environment can be improved with the familiar apt-get.

Try searching for matplotlib on Ubuntu 12 that you have.

python


$ apt-cache search matplotlib
python-matplotlib - Python based plotting system in a style similar to Matlab
python-matplotlib-data - Python based plotting system (data package)
python-matplotlib-dbg - Python based plotting system (debug extension)
python-matplotlib-doc - Python based plotting system (documentation package)
python-mpltoolkits.basemap - matplotlib toolkit to plot on map projections
python-mpltoolkits.basemap-data - matplotlib toolkit to plot on map projections (data package)
python-mpltoolkits.basemap-doc - matplotlib toolkit to plot on map projections (documentation)
python-scitools - Python library for scientific computing
python-wxmpl - Painless matplotlib embedding in wxPython
python-mpmath - library for arbitrary-precision floating-point arithmetic
python-mpmath-doc - library for arbitrary-precision floating-point arithmetic - Documentation

As far as the result is seen, in the case of Ubuntu 12, matplotlib seems to be provided only in Python2. It seems that Python3 is also available for Ubuntu14 ...

So matplotlib in Python2

Install python-matplotlib. By the way, the version of Python2 installed on Ubuntu 12 is 2.7.3.

$ sudo apt-get install python-matplotlib

I installed it smoothly, so I got the following sample in Pyplot tutorial ...

pyplot_simple.py


import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

I will try it.

$ python pyplot_simple.py
Traceback (most recent call last):
  File "pyplot_simple.py", line 3, in <module>
    import matplotlib.pyplot as plt
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 95, in <module>
    new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/__init__.py", line 25, in pylab_setup
    globals(),locals(),[backend_name])
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 8, in <module>
    import Tkinter as Tk, FileDialog
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
    raise ImportError, str(msg) + ', please install the python-tk package'
ImportError: No module named _tkinter, please install the python-tk package

It looks like an error. When I read the message, I installed python-tk. Since it says something like this, install it.

$ sudo apt-get install python-tk

Try running it again. 16-06-29 pyplot_simple2.png

It was displayed! I thought I would have a harder time, but it was smoother than I expected. Thanks to the package being prepared.

A little more complicated graph

Try date_demo.py, which looks a little more complicated. The source is as follows.

date_demo.py


import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
yearsFmt = mdates.DateFormatter('%Y')

# load a numpy record array from yahoo csv data with fields date,
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
datafile = cbook.get_sample_data('goog.npy')
try:
    # Python3 cannot load python2 .npy files with datetime(object) arrays
    # unless the encoding is set to bytes. Hovever this option was
    # not added until numpy 1.10 so this example will only work with
    # python 2 or with numpy 1.10 and later.
    r = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
    r = np.load(datafile).view(np.recarray)

fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)


# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)

datemin = datetime.date(r.date.min().year, 1, 1)
datemax = datetime.date(r.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)


# format the coords message box
def price(x):
    return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)

# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()

plt.show()

When I run it ...

$ python date_demo.py
Traceback (most recent call last):
  File "t2.py", line 17, in <module>
    datafile = cbook.get_sample_data('goog.npy')
  File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 682, in get_sample_data
    return open(f, 'rb')
IOError: [Errno 2] No such file or directory: "/etc/'/usr/share/matplotlib/sampledata'/goog.npy"

It looks like an error. It seems to refer to the strange path /etc/'/usr/share/matplotlib/sampledata'/goog.npy. I wonder if there is a place to set it somewhere ... Unfortunately I do not have that much knowledge yet, so I will search for goog.npy for the time being.

$ find /usr -name "goog.npy"
/usr/share/matplotlib/sampledata/goog.npy

I found it, so change it to the full path ...

@@ -12,7 +12,7 @@ yearsFmt = mdates.DateFormatter('%Y')
 # open, close, volume, adj_close from the mpl-data/example directory.
 # The record array stores python datetime.date as an object array in
 # the date column
-datafile = cbook.get_sample_data('goog.npy')
+datafile = cbook.get_sample_data('/usr/share/matplotlib/sampledata/goog.npy')
 try:
     # Python3 cannot load python2 .npy files with datetime(object) arrays
     # unless the encoding is set to bytes. Hovever this option was

Try running it again.

$ python date_demo.py

date_demo.png

It was displayed! Although I was able to draw the graph more easily than I expected, this time it was a problem with the path of the sample data, but I was a little worried when I thought that other problems might occur.

Recommended Posts

Use matplotlib on Ubuntu 12 & Python
build Python on Ubuntu
Install Python 3.3 on Ubuntu 12.04
[Python] Japanese localization of matplotlib on Ubuntu
Build Python3.5 + matplotlib environment on Ubuntu 12 using Anaconda
Set up Python 3.4 on Ubuntu
Set matplotlib font on ubuntu
Put Python 3.x on Ubuntu
Install OpenCV on Ubuntu + python
Introducing TensorFlow on Ubuntu + Python 2.7
Use Python on Windows (PyCharm)
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Install Python 3.8 on Ubuntu 18.04 (OS standard)
Prepare Python development environment on Ubuntu
Building a Python environment on Ubuntu
[Python / matplotlib] Understand and use FuncAnimation
Install Python 3.8 on Ubuntu 20.04 (OS standard)
Introducing Python using pyenv on Ubuntu 20.04
Preparing python using vscode on ubuntu
Draw Japanese with matplotlib on Ubuntu
Install Python 3.9 on Ubuntu 20.04 (OS standard?)
Install confluent-kafka for Python on Ubuntu
Install Python 2.7 on Ubuntu 20.04 (OS standard?)
Build Python 3.8 + Pipenv environment on Ubuntu 18.04
Sakura Use Python on the Internet
OpenCV3 & Python3 environment construction on Ubuntu
Python on Windows
twitter on python3
Build Python3 and OpenCV environment on Ubuntu 18.04
Python virtual environment and packages on Ubuntu
Shebang on Ubuntu 20.04
#Python basics (#matplotlib)
Steps to install Python environment on Ubuntu
Memorandum on how to use gremlin python
Created Ubuntu, Python, OpenCV environment on Docker
Use without installing python 2.x on Windows
python on mac
My matplotlib (python)
Use Python external module on Sakura Internet
Install python on xserver to use pip
Use Django's ImageField on App Engine / Python
Python on Windbg
Install pyenv and Python 3.6.8 on Ubuntu 18.04 LTS
Add words to MeCab's user dictionary on Ubuntu for use in Python
Install Python3, numpy, pandas, matplotlib, etc. on Windows
Easy way to use Python 2.7 on Cent OS 6
Build python environment with pyenv on EC2 (ubuntu)
Install python package in personal environment on Ubuntu
[Procedure memo] Install Python3 + OpenSSL locally on Ubuntu
How to use Python Kivy ④ ~ Execution on Android ~
Python development on Ubuntu on AWS EC2 (using JupyterLab)
Use the latest version of PyCharm on Ubuntu
How to run MeCab on Ubuntu 18.04 LTS Python
[Venv] Create a python virtual environment on Ubuntu
Comfortable use of Magic Trackpad 2 on Ubuntu desktop
At the time of python update on ubuntu
Until you use PhantomJS with Python on Heroku
Install MongoDB on Ubuntu 16.04 and operate via python
Visualize grib2 on a map with python (matplotlib)
Use thingsspeak from python
Python conda on cygwin