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.
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
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()
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()
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()
That's it. I will add it again if I come up with it in the future. Well then.
Recommended Posts