Matplotlib_Study01
極坐标
雷達圖
代碼:
# 标簽
labels = np.array(['藝術A', '調研I', '實際R', '正常C', '企業E', '社會S'])
# 資料個數
dataLenth = 6
# 資料
data = np.array([1, 4, 3, 6, 4, 8])
# 生成從0開始到6.28的6個并且不可能包括6.28 的一個數組
# 這裡又将原數組賦給另一個變量跟之後的數組處理分開是因為在繪制标簽時并不需要處理數組
angles1 = np.linspace(0, 2 * np.pi, dataLenth, endpoint=False)
print(angles1)
# 這裡需要在資料中多添加一個資料跟第一個元素一緻,實作閉合
data = np.concatenate((data, [data[0]])) # 閉合
angles = np.concatenate((angles1, [angles1[0]])) # 閉合
fig = plt.figure(figsize=(10, 10))
# 因為是雷達圖 需要極坐标系,是以polar參數必須true
ax = fig.add_subplot(1, 1, 1, polar=True) # polar參數!!
# 繪制線條,處理過的數組,o表示用圓點來表示節點
ax.plot(angles, data, '-o', linewidth=2) # 畫線
# 将框起來的資料使用顔色填充
ax.fill(angles, data, facecolor='b', alpha=0.25) # 填充
# 設定标簽,這裡不需要處理的數組
ax.set_thetagrids(angles1 * 180 / np.pi, labels, fontproperties="SimHei")
# 設定title
ax.set_title("matplotlib雷達圖", va='bottom', fontproperties="SimHei")
# 繪制第二條資料
ax.plot(angles, [1, 5, 1, 8, 0, 11, 1], '-o', linewidth=2) # 畫線
ax.fill(angles, [1, 5, 1, 8, 0, 11, 1], facecolor='r', alpha=0.25) # 填充
# ax.set_thetagrids(angles1 * 180 / np.pi, labels, fontproperties="SimHei")
ax.set_rlim(0, 11)
#
ax.grid(True)
plt.legend(
['group of 1 clusters, %d perple' % sum(data[1:]), 'group of 2 clusters, %d perple' % sum([1, 5, 1, 8, 1, 6])],
loc='upper right', bbox_to_anchor=(1.1, 0.9))
plt.show()
效果:
不能正常顯示中文
from matplotlib.font_manager import FontProperties
myfont = FontProperties(fname=“C:\Windows\Fonts\simsun.ttc”, size=20)
通過改變matplotlib 使用matplotlib的字型管理器指定字型檔案。
但是,為字型添加的大小,加粗,斜體的樣式都沒有效果。
總結:
在顯示中文時,可以使用font_manager 子產品來設定字型檔案,但添加不了樣式。
更改後
代碼:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.font_manager import FontProperties
# 設定字型檔案
myfont = FontProperties(fname="C:\Windows\Fonts\simsun.ttc", style='italic', size=20, family='serif')
# matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 顯示中文标簽
# matplotlib.rcParams['axes.unicode_minus'] = False # 這兩行需要手動設定
# # 建立視窗
# fig = plt.figure(1)
# # 第一行第一列第一個,子圖
# ax1 = fig.add_subplot(1, 1, 1, polar=True)
# theta=np.arange(0,2*np.pi,0.02)
# ax1.plot(theta,2*np.ones_like(theta),lw=2)
# ax1.plot(theta,theta/6,linestyle='--',lw=2)
# plt.show()
# =======自己設定開始============
# 标簽
labels = np.array(['藝術A', '調研I', '實際R', '正常C', '企業E', '社會S'])
# 資料個數
dataLenth = 6
# 資料
data = np.array([1, 2, 3, 2, 2, 3])
# ========自己設定結束============
angles1 = np.linspace(0, 2 * np.pi, dataLenth, endpoint=False)
# print(angles1)
data = np.concatenate((data, [data[0]])) # 閉合
angles = np.concatenate((angles1, [angles1[0]])) # 閉合
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(1, 1, 1, polar=True) # polar參數!!
ax.plot(angles, data, '-o', linewidth=2) # 畫線
ax.fill(angles, data, facecolor='b', alpha=0.25) # 填充
ax.set_thetagrids(angles1 * 180 / np.pi, labels)
font = {
# 'family': 'serif',
'style': 'italic',
'weight': 'bold',
'color': 'red',
'size': 25,
# 'fontproperties': 'KaiTi'
}
# 在使用時傳入參數即可
ax.set_title("matplotlib嗷嗷嗷", loc='center', fontdict=font, fontproperties=myfont)
ax.plot(angles, [1, 2, 1, 3.5, 0, 3, 1], '-o', linewidth=2) # 畫線
ax.fill(angles, [1, 2, 1, 3.5, 0, 3, 1], facecolor='r', alpha=0.25) # 填充
ax.set_thetagrids(angles1 * 180 / np.pi, labels, fontproperties='SimHei')
# 設定坐标軸刻度顯示
ax.set_rlim(-2, 3.5, auto=False, emit=True)
ax.grid(True)
plt.legend(
['group of 1 clusters, %d perple' % sum(data[1:]), 'group of 2 clusters, %d perple' % sum([1, 5, 1, 8, 1, 6])],
loc='upper right', bbox_to_anchor=(1.1, 0.9))
plt.show()
補充學習:
numpy
linspace
在指定的間隔内傳回均勻間隔的數字
參數傳遞 (start, stop, num=50, endpoint=True, retstep=False, dtype=None)
從start開始,stop結束,會有num個數值傳回。endpoint為True時一定包括stop,false時一定不包括。
concatenate
用于拼接 numpy數組。
參數傳遞 concatenate((array1, array2 …), axis=0 或 1)
axis預設會導緻傳回一維結果,axis=0行數增加,axis=1列數增加
matplotlib
設定legend 的位置
plt.legend(
[‘group of 1 clusters, %d perple’ % sum(data[1:]), ‘group of 2 clusters, %d perple’ % sum([1, 5, 1, 8, 1, 6])],
loc=‘upper right’, bbox_to_anchor=(1.1, 0.9))
loc 參數
bbox_to_anchor被賦予的二進制組中,num1用于控制legend的左右移動,值越大越向右邊移動,num2用于控制legend的上下移動,值越大,越向上移動。用于微調圖例的位置。
柱狀圖
代碼:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
# 建立視窗,可以通過指定num為視窗指定ID
fig = plt.figure(figsize=(10, 10))
x_index = np.arange(1, 11, step=2) # 柱的索引
x_data = ('A', 'B', 'C', 'D', 'E')
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
y3_data = (30, 21, 23, 15, 24)
bar_width = 0.35 # 定義一個數字代表每個獨立柱的寬度
rects1 = plt.bar(x_index, y1_data, width=bar_width, alpha=0.4, color='b', label='legend1') # 參數:左偏移、高度、柱寬、透明度、顔色、圖例
rects2 = plt.bar(x_index + bar_width, y2_data, width=bar_width, alpha=0.5, color='r',
label='legend2') # 參數:左偏移、高度、柱寬、透明度、顔色、圖例
rects3 = plt.bar(x_index + 2*bar_width, y3_data, width=bar_width, alpha=0.5, color='g',
label='legend3') # 參數:左偏移、高度、柱寬、透明度、顔色、圖例
# 關于左偏移,不用關心每根柱的中心不中心,因為隻要把刻度線設定在柱的中間就可以了
plt.xticks(x_index + 2*bar_width / 2, x_data) # x軸刻度線
# 設定圖像和邊緣的距離,相比于tight_layout 更加精确
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, hspace=0.1, wspace=0.1)
plt.legend() # 顯示圖例
font = {
# 'family': 'serif',
'style': 'italic',
'weight': 'bold',
'color': 'red',
'size': 25,
# 'fontproperties': 'KaiTi'
}
# 這裡顯示中文的問題跟昨天的一樣,對于中文添加不上斜體的樣式但可以添加顔色,字型大小。
plt.title("matplotlib柱狀圖", color='green', weight='bold', style='oblique', fontproperties='SimHei', fontsize=18)
plt.tight_layout() # 自動控制圖像外部邊緣,此方法不能夠很好的控制圖像間的間隔
plt.show()
效果:
直方圖
代碼:
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
fig, (ax0, ax1) = plt.subplots(nrows=2, figsize=(12, 9))
sigma = 1 # 标準差
mean = 0 # 均值
x = mean + sigma * np.random.randn(10000) # 正态分布随機數
# 繪制直方圖
ax0.hist(x, bins=40, density=False, stacked=False, histtype='bar', facecolor='yellowgreen',
alpha=0.75) # normed是否歸一化,histtype直方圖類型,facecolor顔色,alpha透明度
ax1.hist(x, bins=20, density=False, stacked=False, histtype='bar', facecolor='pink', alpha=0.75, cumulative=True,
rwidth=0.8) # bins柱子的個數,cumulative是否計算累加分布,rwidth柱子寬度
# 可以同時設定主圖的标題和子圖示題,實作主标題和副标題的效果
# 設定總圖中的标題
plt.suptitle("matplotlib_main_title", fontsize=18)
# 設定子圖示題
ax0.set_title('matplotlib_slave1_title')
ax1.set_title('matplotlib_slave2_title')
plt.show() # 所有視窗運作
效果:
散點圖
代碼:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
x = np.random.random(100)
print(x)
y = np.random.random(100)
print(y)
print(x*1000)
ax.scatter(x, y, s=x * 1000, c='y', marker=(5, 1), alpha=0.5, lw=1,
facecolors='none') # x橫坐标,y縱坐标,s圖像大小,c顔色,marker圖檔,lw圖像邊框寬度
# maker 支援'.'(點标記)、','(像素标記)、'o'(圓形标記)、'v'(向下三角形标記)、'^'(向上三角形标記)、'<'(向左三角形标記)、'>'(向右三角形标記)、'1'(向下三叉标記)、'2'(向上三叉标記)、'3'(向左三叉标記)、'4'(向右三叉标記)、's'(正方形标記)、'p'(五地形标記)、'*'(星形标記)、'h'(八邊形标記)、'H'(另一種八邊形标記)、'+'(加号标記)、'x'(x标記)、'D'(菱形标記)、'd'(尖菱形标記)、'|'(豎線标記)、'_'(橫線标記)
# s 訓示 散點的大小,c 訓示顔色,lw訓示散點邊框寬度,alpha訓示透明度
# edgecolors,指定散點邊框的顔色。
plt.show()
效果:
補充:
ax.spines[‘top’].set_visible(False)
ax.spines[‘right’].set_visible(False)
可以通過以上代碼,将grid 布局,非類目軸的圖表的外框線去除。
折線圖
代碼:
import matplotlib.pyplot as plt
from matplotlib import pyplot
import matplotlib
# 設定視窗大小
fig = plt.figure(figsize=(20, 8))
ax = fig.add_subplot(1, 1, 1)
x = range(2, 26, 2)
y = [15, 13, 14.5, 17, 20, 25, 26, 26, 27, 22, 18, 15]
# 設定坐标軸刻度顯示,預設的過于粗糙
plt.xticks(x) # 這裡傳入的x就是x軸的清單
plt.yticks(range(min(y), max(y) + 1))
# 設定坐标軸的标簽顯示
plt.xlabel('時間', fontproperties='SimHei')
plt.ylabel('溫度', fontproperties='SimHei')
plt.title('時間溫度表', fontproperties='SimHei', color='red', fontsize=18, style='italic')
# 是否顯示網格(啟用grid布局)
plt.grid()
# 繪制,設定圖例表标簽
pyplot.plot(x, y, label='legend1')
# 顯示圖例
plt.legend()
plt.show()
效果:
餅圖
代碼:
import matplotlib.pyplot as plt
import matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文标簽
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
labels = ['娛樂', '育兒', '飲食', '房貸', '交通', '其它']
sizes = [2, 5, 12, 70, 2, 9]
explode = (0, 0, 0, 0.1, 0, 0)
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.0f%%', shadow=True, startangle=150)
plt.title("餅圖示例-8月份家庭支出")
plt.show()
效果:
補充:
ax.pie() 參數詳解
pie(x, explode=None, labels=None, colors=None, autopct=None,
pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
radius=None, counterclock=True, wedgeprops=None, textprops=None,
center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None)
x:每一塊餅圖的比例,為必填項,如果sum(x)>1,會将多出的部分進行均分;
labels : 每一塊餅圖外側顯示的說明文字;
explode : 每一塊餅圖 離開中心距離,預設值為(0,0),就是不離開中心;
colors:數組,可選參數,預設為:None;用來标注每塊餅圖的matplotlib顔色參數序列。如果為None,将使用目前活動環的顔色。
shadow :是否陰影,預設值為False,即沒有陰影,将其改為True,顯示結果如下圖所示;
autopct :控制餅圖内百分比設定,可以使用format字元串或者format function;
startangle :起始繪制角度,預設圖是從x軸正方向逆時針畫起,如設定startangle=90則從y軸正方向畫起;
counterclock:指定指針方向;布爾值,可選參數,預設為:True,即逆時針。将值改為False即可改為順時針。
labeldistance : label繪制位置,相對于半徑的比例, 如<1則繪制在餅圖内側,預設值為1.1;
radius :控制餅圖半徑;浮點類型,可選參數,預設為:None。如果半徑是None,将被設定成1。
pctdistance : 類似于labeldistance,指定autopct的位置刻度,預設值為0.6;
**textprops **:設定标簽(labels)和比例文字的格式;字典類型,可選參數,預設值為:None。
将餅圖顯示為正圓形,plt.axis( );
詞雲
代碼:
import matplotlib.pyplot as plt
import matplotlib
from wordcloud import WordCloud
import jieba
from imageio import imread
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# 讀取檔案内容
with open(r'C:\Users\Administrator\Desktop\wordcloud_test.txt', 'r') as f:
text = f.read()
# 分詞
wcsplit = jieba.lcut(text)
# 拼接成字元串
words = " ".join(wcsplit)
# 讀取一張圖檔作為詞雲的背景
shape = imread(r'C:\Users\Administrator\Pictures\Saved Pictures\t.jpg')
# 建立wordcloud 對象
mywordcloud = WordCloud(
font_path=r'C:\Windows\Fonts\simhei.ttf', # 字型
scale=8,
margin=1, # 頁邊距
background_color='black', # 背景色
mask=shape, # 形狀
max_words=1500, # 包含的最大詞量
min_font_size=14, # 最小的字型
max_font_size=95, # 最大字型
random_state=4567
).generate(words)
# 顯示圖像
ax.imshow(mywordcloud)
# 去除坐标軸
ax.axis("off")
plt.show()
效果:
堆疊柱狀圖
代碼:
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# 添加柱狀圖的具體數值
def auto_labels(res):
for rect in res:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2. - 0.2, 1.03 * height, '%s' % float(height))
# label
labels = ['G1', 'G2', 'G3', 'G4', 'G5', 'G6'] # 級别
men_means = np.random.randint(20, 35, size=6)
women_means = np.random.randint(20, 35, size=6)
men_std = np.random.randint(1, 7, size=6)
women_std = np.random.randint(1, 7, size=6)
width = 0.35
# 畫圖
a = plt.bar(labels, # 橫坐标
men_means, # 柱⾼
width, # 線寬
# yerr=0, # 誤差條
label='Men') # 标簽
# 堆疊柱狀圖,再畫
b = plt.bar(labels, women_means, width, bottom=men_means, label='Women')
# 設定兩坐标軸标簽
plt.ylabel('Scores')
plt.xlabel('Species')
plt.title('Scores by group and gender')
# auto_labels(a)
# 填寫數值
auto_labels(b)
plt.legend()
plt.show()
效果: