# 引入模組
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = pd.period_range(pd.datetime.now(), periods=200, freq='d')
x = x.to_timestamp().to_pydatetime()
# 產生三組,每組 200 個隨機常態分布元素
y = np.random.randn(200, 3).cumsum(0)
plt.plot(x, y)
plt.show()
#==========
#==========
#線圖
x = np.array([1, 2, 3])
y1 = np.array([1, 2, 3])
y2 = np.array([10, 20, 30])
plt.figure(figsize=(8,4))
plt.plot(x,y1,label="line-1",color="red",linewidth=2)
# b--粗體虛線
plt.plot(x,y2,"b--",label="line-2")
plt.xlabel("x label")
plt.ylabel("y label")
plt.title("PyPlot First Example")
#plt.ylim(-1.2,1.2)
plt.legend()
plt.show()
#==========
#==========
# 長條圖
labels = ['Physics', 'Chemistry', 'Literature', 'Peace']
foo_data = [3, 6, 10, 4]
bar_width = 0.5
xlocations = np.array(range(len(foo_data))) + bar_width
plt.bar(xlocations, foo_data, width=bar_width)
plt.title('Stock Price')
plt.show()
# 直方圖
normal_samples = np.random.normal(size=100) # 生成 100 組標準常態分配(平均值為 0,標準差為 1 的常態分配)隨機變數
plt.hist(normal_samples)
plt.show()
#==========
#==========
# 散佈圖 + 迴歸
num_points = 100
gradient = 0.5
x = np.array(range(num_points))
y = np.random.randn(num_points) * 10 + x * gradient
fig, ax = plt.subplots(figsize=(8, 4))
ax.scatter(x, y)
m, c = np.polyfit(x, y, 1) # 使用 Numpy 的 polyfit,參數 1 代表一維,算出 fit 直線斜率
ax.plot(x, m * x + c) # 使用 y = m * x + c 斜率和常數匯出直線
fig.suptitle('Scatter with regression')
plt.show()
#==========
# 圓餅圖
labels = ['A','B','C','D','E']
data = np.random.randint(1, 11, 5) # 生成
x = np.arange(len(data))
plt.pie(data, labels=labels, autopct='%1.1f%%')
plt.show()
#==========
# 盒鬚圖
normal_examples = np.random.normal(size = 100) # 生成 100 組標準常態分配(平均值為 0,標準差為 1 的常態分配)隨機變數
plt.boxplot(normal_examples)
plt.show()
# 把圖儲存,要放在plt.show()之前
plt.savefig("C:/savefig/hist.png")
沒有留言:
張貼留言