[PYTHON] Summary of frequently used commands in matplotlib

I often forget the details when drawing graphs with IPython & matplotlib, so I summarized them. I'm talking about what number it is, but I hope you find it helpful.

Import modules to use every time

If you create 00_import.py etc. under ~ / .ipython / profile_default / startup / It runs automatically when IPython starts.

00_import.py


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re

Draw a line graph with plot

Isn't this the place you often use?

sample_1.py


x = np.arange(-10, 10, 0.1)
y = x**3

plt.figure(figsize=(6, 4))  # set aspect by width, height

plt.xlim(min(x), max(x))
plt.ylim(min(y), max(y))  # set range of x, y

plt.xticks(np.arange(min(x), max(x)+2, 2))
plt.yticks(np.arange(min(y), max(y)+200, 200))  # set frequency of ticks

plt.plot(x, y, color=(0, 1, 1), label='y=x**3')  # color can be set by (r, g, b) or text such as 'green'

plt.hlines(0, min(x), max(x), linestyle='dashed', linewidth=0.5)  # horizontal line
plt.vlines(0, min(y), max(y), linestyle='dashed', linewidth=0.5)  # vertical line

plt.legend(loc='upper left')  # location can be upper/lower/center/(none) and right/left/(none)
plt.title('Sample 1')
plt.show()

graph_sample1.png

Draw separately on the 1st and 2nd axes

I often need this, but I forgot it every time ... When manipulating an ax object, the method name changes a little compared to plt. Untara (set_ is required). The link below makes it easy to understand the relationship between the figure object and the ax object. http://ailaby.com/matplotlib_fig/

sample_2.py


# just prepare data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = x

fig, ax = plt.subplots(figsize=(5,5))  # create figure and axes object
ax.plot(x, y1, label='sin(x)', color='red')  # plot with 1st axes

ax.set_ylabel('y=sin(x)')  # set label name which will be shown outside of graph
ax.set_yticks(np.arange(-1, 1+0.2, 0.2))

ax2 = ax.twinx()  # create 2nd axes by twinx()!
ax2.set_ylabel('y=x')
ax2.plot(x, y2, label='x', color='blue')  # plot with 2nd axes

ax.set_xlim(0, 5)  # set range

ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.title('Sample 2')
plt.show()

graph_sample2.png

Draw a scatter plot with letters

Personally, I often annotate each point on the scatter plot with a number or score, so I put it in.

sample_3.py


pos_x = [1.0, 1.5, 2.1, 2.7, 3.0]  # x of positions
pos_y = [0.7, 0.9, 1.0, 1.3, 1.5]  # y of positions
time = [1, 2, 3, 4, 5]  # time of each positions

# draw points
plt.scatter(pos_x, pos_y, color='red', label='Position')

# annotate each points
for i, t in enumerate(time):
    msg = 't=' + str(t)
    plt.annotate(msg, (pos_x[i], pos_y[i]))  # x,y need brackets

plt.title('Sample 3')    
plt.legend(loc='upper left')
plt.show()

graph_sample3.png

That's it. I will add it again if I come up with it in the future. Well then.

Recommended Posts

Summary of frequently used commands in matplotlib
[Anaconda3] Summary of frequently used commands
Summary of frequently used commands of django (beginner)
Frequently used commands in virtualenv
[Python/Django] Summary of frequently used commands (2) <Installing packages>
Summary of frequently used commands (with petit commentary)
A collection of commands frequently used in server management
8 Frequently Used Commands in Python Django
List of frequently used Linux commands
[Linux] Review of frequently used basic commands 2
Summary of methods often used in pandas
[Linux] List of Linux commands used in practice
[Linux] Review of frequently used basic commands
pyenv Frequently used commands
Frequently used tmux commands
Frequently used Linux commands
Frequently used Linux commands
Frequently used linux commands
Frequently used pip commands
Summary of what was used in 100 Pandas knocks (# 1 ~ # 32)
Summary of tools used in Command Line vol.8
Summary of tools used in Command Line vol.5
Summary of evaluation functions used in machine learning
Summary of frequently used Python arrays (for myself)
[Linux command] A memorandum of frequently used commands
Selenium webdriver Summary of frequently used operation methods
[Python/Django] Summary of frequently used commands (4) -Part 2- <Production operation: Amazon EC2 (Amazon Linux 2)>
[Python/Django] Summary of frequently used commands (4) -Part 1- <Production operation: Amazon EC2 (Amazon Linux 2)>
Summary of Linux (UNIX) commands that appeared in Progate
Frequently used subpackages of SciPy
Display a list of frequently used commands on Zsh
Summary of how to write .proto files used in gRPC
Linux Frequently Used Commands [Personal Memo]
Summary of various operations in Tensorflow
Grammar summary often used in pandas
[Linux] Frequently used Linux commands (file operation)
Frequently used Linux commands (for beginners)
[Linux] Frequently used Linux commands (folder operation)
[Python] A memo of frequently used phrases (by myself) in Python scripts
matplotlib summary
Disk-related commands often used in Ubuntu (memories)
Python + Selenium Frequently used operation method summary
[Linux] Summary of middleware version confirmation commands
[python] Frequently used techniques in machine learning
Summary of various for statements in Python
Jupyter, numpy, matplotlib notes used in reports
Summary of stumbling blocks in installing CaboCha
Summary of petit techniques for Linux commands
Separation of design and data in matplotlib
Summary of modules and classes in Python-TensorFlow2-
Summary of built-in methods in Python list
[Machine learning] List of frequently used packages
Modules of frequently used functions in Python (such as reading external files)
Summary of OSS tools and libraries created in 2016
Summary of how to import files in Python 3
List of frequently used built-in functions and methods
Utilization of recursive functions used in competition pros
Full disclosure of methods used in machine learning
Summary of how to use MNIST in Python
Fix the argument of the function used in map
Put the second axis in 2dhistgram of matplotlib