Matplotlib

折線圖

In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

plt.plot([1, 4, 3, 1, 5])
plt.show()
In [2]:
x = np.linspace(0, 10, 101)
y = x**2-6*x-3
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
Out[2]:
Text(0,0.5,'y')
In [3]:
x = np.random.rand(20, 2)
p = plt.plot(x)
plt.legend(p, ('a', 'b'))
Out[3]:
<matplotlib.legend.Legend at 0x11b854dd8>
In [4]:
x = np.linspace(0, 10, 21)
plt.plot(x, x, 'r^')
plt.plot(x, x**2, '--')
plt.plot(x, x**3, 'go')
Out[4]:
[<matplotlib.lines.Line2D at 0x11ba01860>]
In [5]:
plt.plot?

長條圖

In [6]:
x = np.arange(10)
y = np.array([5, 9, 4, 8, 7, 4, 3, 1, 2, 9])
plt.bar(x, y)
Out[6]:
<BarContainer object of 10 artists>

散佈圖

In [7]:
x = np.random.rand(30)
y = np.random.rand(30)
plt.scatter(x, y)
Out[7]:
<matplotlib.collections.PathCollection at 0x11bb43e48>

多張圖

In [8]:
x = np.linspace(0, 5, 21)
plt.figure()

plt.subplot(231)
plt.plot(x, x)

plt.subplot(232)
plt.plot(x, x**2)

plt.subplot(233)
plt.plot(x, x**3)

plt.subplot(234)
plt.plot(x, x**0.5)

plt.subplot(235)
plt.plot(x, x**0.25)

plt.subplot(236)
plt.plot(x, x*2)
Out[8]:
[<matplotlib.lines.Line2D at 0x11bd21550>]
In [9]:
x = np.linspace(-10, 10, 201)
y = 5*(x**2)-3*x+4
plt.plot(x, y)
Out[9]:
[<matplotlib.lines.Line2D at 0x11bdfd748>]

處理日期

In [10]:
from datetime import datetime
x = datetime.strptime('2020-06-14', '%Y-%m-%d')
print(type(x))
print(x)
<class 'datetime.datetime'>
2020-06-14 00:00:00
In [11]:
datetime.now() # 當前時間
Out[11]:
datetime.datetime(2020, 6, 14, 0, 14, 6, 359042)
In [12]:
s = datetime.strftime(datetime.now(), '%Y-%m-%d')
print(s)
2020-06-14
In [14]:
import matplotlib.dates as mdates
s = '''2016-06-01 782
2016-07-01 679
2016-08-01 791
2016-09-01 111
2016-10-01 1177
2016-11-01 885
2016-12-01 2054
2017-01-01 867
2017-02-01 776
2017-03-01 961
2017-04-01 926
2017-05-01 792
2017-06-01 884
2017-07-01 700
2017-08-01 872
2017-09-01 1193
2017-10-01 1063
2017-11-01 1012
2017-12-01 230
2018-01-01 859
2018-02-01 899
2018-03-01 895
2018-04-01 875
2018-05-01 979
2018-06-01 711
2018-07-01 697
2018-08-01 970
2018-09-01 1122'''
s = s.split('\n')
date = []
num = []
for i in range(len(s)):
    s[i] = s[i].split()
    num.append(int(s[i][1]))
    date.append(datetime.strptime(s[i][0], '%Y-%m-%d'))

fig, ax = plt.subplots()
ax.xaxis.set_major_locator(mdates.YearLocator()) # 設定大刻度
ax.xaxis.set_minor_locator(mdates.MonthLocator()) # 設定小刻度
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) # 設定大刻度標示

plt.bar(date, num, width=10)
plt.show()