# 使用 Matplotlib 绘图

GrpahViz 和 PlantUML 主要是用来绘制逻辑相关的图，比如时序图、框图、思维导图（仔细想想好像用到的地方并不多）

## 折线图

import matplotlib
import matplotlib.pyplot as plt
import sys

matplotlib.use("svg")

plt.plot([1,2,3,4,5],[1,4,9,16,25])
plt.savefig(sys.stdout)


import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import sys

x = np.arange(0.0,10,0.01)
y = x ** 2

matplotlib.use("svg")

plt.plot(x, y)
plt.savefig(sys.stdout)


## 让折线更好看

import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as mpatches

matplotlib.use("svg")

t = np.arange(0., 5., 0.2)

plt.title("title")
plt.xlabel("time (s)")
plt.ylabel("value")

plt.figure(1)
plt.subplot(211)
plt.plot(t, t, 'r--', t, t*2, 'bs-', t, t**2, 'g^')
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.subplot(212)
plt.plot(t, t, 'r--', label="test1")
plt.plot(t, t*2, 'bs-', label="text2")
plt.plot(t, t**2, 'g^', label="text3")
plt.grid(True)
plt.text(4, 15, "$(4,15)$")

plt.savefig(sys.stdout)


## 饼图

import sys
import matplotlib
import matplotlib.pyplot as plt

matplotlib.use("svg")

plt.figure()
labels = ["A","B","C","D"]
sizes = [46,253,321,66]
colors = ['red','yellowgreen','lightskyblue','yellow']
explode = (0,0,0,0)
patches,text1,text2 = plt.pie(
sizes,
explode = explode,
labels = labels,
colors = colors,
autopct = '%3.2f%%',
startangle = 90,
pctdistance = 0.6
)

plt.savefig(sys.stdout)


## 直方图

import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.use("svg")

data = np.random.randn(10000)

plt.figure()
plt.hist(data, bins=40, facecolor="blue", edgecolor="black", alpha=0.7)

plt.savefig(sys.stdout)


## 条形图

import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.use("svg")

label_list = ['2014', '2015', '2016', '2017']
num_list1 = [20, 30, 15, 35]
num_list2 = [15, 30, 40, 20]
x = range(len(num_list1))

rects1 = plt.bar(x=x, height=num_list1, width=0.4, alpha=0.8, color='red', label="A")
rects2 = plt.bar(x=[i + 0.4 for i in x], height=num_list2, width=0.4, color='green', label="B")
plt.ylim(0, 50)

plt.xticks([index + 0.2 for index in x], label_list)
plt.legend()

for rect in rects1:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")
for rect in rects2:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height+1, str(height), ha="center", va="bottom")

plt.savefig(sys.stdout)