matplotlib使用示例——直線座標系、極座標系、柱形圖、直方圖、散點圖、氣泡圖、餅圖、多邊形、3D圖、盒圖

一、直線座標系

# encoding=utf-8
"""
@Time : 2020/1/9 17:15 
@Author : LiuYanZhe
@File : demo1.py 
@Software: PyCharm
@Description: 直線座標系
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

# 數據
x = np.arange(-10, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.power(x, 2)
y4 = np.power(x, 3)

# 創建畫布
fig, ax_arr = plt.subplots(2, 1)  # 同時創建一個窗口和2個子圖
# 創建子圖
ax1 = ax_arr[0]
ax2 = ax_arr[1]
axes = plt.axes([0.2, 0.3, 0.1, 0.1], facecolor='y')  # 添加子圖,不擠壓原圖空間,覆蓋在原圖之上
# 畫布設置
# fig=plt.gcf()   # 獲取當前figure
# fig.set_size_inches(5, 6)   # 設置畫布大小
fig.subplots_adjust(hspace=0.3, top=0.95)  # 子圖之間保留的寬度,與頂部保持的寬度
# 子圖設置
ax1.set_title('sin/cos')  # 設置標題
ax2.set_title('x^2/x^3')
ax1.set_xlim(-5, 5)  # 設置橫縱座標範圍
ax1.set_ylim(-1, 1)
ax2.set_xlim(-3, 3)
ax2.set_ylim(0, 9)
xmajorLocator = MultipleLocator(2)  # 設置座標顯示格式,刻度差爲2的倍數
ax2.xaxis.set_major_locator(xmajorLocator)
ax1.grid(b=True, which='major', axis='both', alpha=0.5,
         color='skyblue', linestyle='--', linewidth=1)  # 繪製網格 參數:which=major(繪製大刻度)/minor(小刻度)/both,axis=x/y/both
ax2.xaxis.grid(True, which='major')  # 設置網格-xy單獨設置
ax2.yaxis.grid(True, which='major')
ax1.set_xticks([])  # 手動設置座標軸刻度(無刻度)
ax1.set_xticks([-5, -2.5, 0, 2.5, 5])  # 手動設置座標軸刻度(無刻度)
# ax2.set_xticklabels(labels=['', 'x1', 'x2', 'x3', 'x4'], rotation=-30, fontsize='small')  # 設置座標軸顯示文本,傾斜角度,字體
# ax1.legend(loc='legned_lyz')    # 顯示圖例
ax1.text(-0.6, 0.1, 'y=sin(x)')  # 指定位置顯示文本
ax1.text(-2, 0.6, 'y=cos(x)')
ax2.annotate('import point (2,4)', xy=(2, 4), xytext=(-1, 7),
             arrowprops=dict(facecolor='red', alpha=0.5, shrink=0.05))  # 添加標註(箭頭)(指向位置,文字位置,顏色,透明度,收縮比例)

# 在子圖中繪製圖像
ax1.plot(x, y1)
ax1.plot(x, y2, linestyle='--', color='r', label='line')  # 繪製點圖並設置格式
ax2.plot(x, y3, marker='.', alpha=0.5, color='g', label='point')
axes.plot(x, y4)
# 保存圖像
plt.savefig('G:/demo.png', dpi=400, bbox_inches='tight')
# 顯示畫布
plt.show()

二、極座標系

# encoding=utf-8
"""
@Time : 2020/1/10 16:42 
@Author : LiuYanZhe
@File : demo2.py
@Software: PyCharm
@Description: 極座標系
"""
import numpy as np
import matplotlib.pyplot as plt

# 數據
x1 = np.arange(-2 * np.pi, 2 * np.pi, 0.1)
x2 = np.arange(0, 2 * np.pi, 0.02)
print('x2:', x2)

# 創建畫布
fig = plt.figure(figsize=(8, 7))    # 創建一個畫板,設定大小,後期添加子圖
fig.subplots_adjust(top=0.95, bottom=0.05)  # 設置畫板
# 添加子圖
ax1 = fig.add_subplot(2, 2, 1)  # 添加一個子圖,將畫板分成1行5列,該子圖爲第1個,直角座標系
ax2 = fig.add_subplot(2, 2, 2, polar=True)  # 添加一個子圖,橫1縱3,第2個,極座標系
ax3 = fig.add_subplot(2, 2, 3, polar=True)  # 添加一個子圖,橫1縱3,第3個,極座標系
ax4 = fig.add_subplot(2, 2, 4, polar=True)  # 添加一個子圖,橫1縱3,第3個,極座標系
# 繪製
ax1.plot(x1, np.sin(x1))
ax1.plot(x1, np.cos(x1))
ax2.plot(x2, np.ones_like(x2))  # np.ones_like()函數返回1,類型和輸入值類型相同
ax2.plot(x2, x2 / 6, linestyle='--', lw=1.5)  # lw爲線寬
ax3.plot(x2, np.sin(x2), color='b', alpha=0.7, linestyle='-.')
ax3.plot(x2, np.cos(x2), color='g', linestyle=':')
ax4.plot(x2, np.cos(4 * x2))
ax4.plot(x2, np.cos(5 * x2), linestyle='--')
# 設置子圖
ax4.set_rgrids(np.arange(0.1, 2, 0.4), angle=45)  # 設置網格
# ax4.set_yticks(np.arange(0.1, 2, 0.4))  # 與上面效果相同
# 保存圖像
plt.savefig('G:/demo2.png', dpi=400, bbox_inches='tight')
# 顯示畫布
plt.show()

三、柱形圖,直方圖,散點圖,氣泡圖

# encoding=utf-8
"""
@Time : 2020/1/10 17:57 
@Author : LiuYanZhe
@File : demo3.py 
@Software: PyCharm
@Description: 柱形圖,直方圖,散點圖,氣泡圖
"""
import numpy as np
import matplotlib.pyplot as plt

# 繪製柱狀圖
ax1 = plt.subplot(1, 1, 1)  # 創建一個畫板,同時創建一個子圖
x_index = np.arange(5)  # 用來做柱的索引
x_data = ('A', 'B', 'C', 'D', 'E')  # 元組,與列表類似,但不可更改
y1_data = (20, 35, 30, 35, 27)
y2_data = (25, 32, 34, 20, 25)
bar_width = 0.35  # 每個柱的寬度
ax1.bar(x_index, y1_data, width=bar_width, alpha=0.6, label='bar2')
ax1.bar(x_index + bar_width, y2_data, width=bar_width, alpha=0.6, label='bar2')
plt.legend()  # 顯示圖例
plt.xticks(x_index + bar_width / 2, x_data)  # 調整x軸刻度標籤
plt.savefig('G:/demo3.png', dpi=400, bbox_inches='tight')
# 繪製直方圖
fig, (ax2, ax3) = plt.subplots(nrows=2)  # 創建一個窗口,同時創建兩個子圖
sigma = 1  # 標準差
avg = 0  # 均值
x = avg + sigma * np.random.randn(10000)  # 正態分佈隨機數
ax2.hist(x, bins=40, density=False, histtype='bar', )  # bins柱子個數,'auto'自動設定,默認爲10;normed是否歸一化;histtype直方圖
ax3.hist(x, bins='auto', density=True, histtype='bar', facecolor='yellowgreen', alpha=0.8, cumulative=True,
         rwidth=0.8)  # cumulative是否計算累加分佈,rwidth柱子寬度
plt.savefig('G:/demo4.png', dpi=400, bbox_inches='tight')
# 繪製氣泡圖-散點圖
fig2 = plt.figure()  # 新建畫板
ax4 = fig2.add_subplot(1, 2, 1)  # 新建子圖
ax5 = fig2.add_subplot(1, 2, 2)  # 新建子圖
x4 = np.random.random(100)  # 產生隨機數據
y4 = np.random.random(100)
# 氣泡圖
ax4.scatter(x4, y4, s=x * 1000, c='g', marker='o', alpha=0.6, lw=1)  # s:圖像大小,c:顏色,marker:圖片,lw:圖片寬度
# 散點圖
ax5.scatter(x4, y4, c='g', marker='o', alpha=0.6, lw=1)  # s:圖像大小,c:顏色,marker:圖片,lw:圖片寬度
plt.savefig('G:/demo5.png', dpi=400, bbox_inches='tight')
# 顯示畫板
plt.show()

四、餅圖,多邊形

# encoding=utf-8
"""
@Time : 2020/1/10 19:25 
@Author : LiuYanZhe
@File : demo4.py 
@Software: PyCharm
@Description: 餅圖,多邊形
"""
import numpy as np
import matplotlib.pyplot as plt

'''餅圖'''
# 數據
n = 10
Z = np.random.rand(n)
lable = ['data1', 'data2', 'data3', 'data4', 'data5', 'data6', 'data7', 'data8', 'data9', 'data10']

# 創建畫板
fig = plt.figure(figsize=(7.5, 4))
fig.subplots_adjust(top=0.95, bottom=0.05, left=0.05, right=0.95)
# 第一個子圖
ax1 = fig.add_subplot(1, 2, 1)
ax1.pie(Z)  # 餅圖
plt.axis('equal')
# 第二個子圖
ax2 = fig.add_subplot(1, 2, 2)
ax2.pie(Z, explode=np.ones(n) * 0.01, labels=lable, colors=['%f' % (i / float(n)) for i in range(n)],
        wedgeprops={'linewidth': 1, 'edgecolor': 'white'})

plt.axis('equal')
plt.xticks([])
plt.yticks([])
# 存儲圖像
plt.savefig('G:/demo4.1.png', dpi=200, bbox_inches='tight')

'''多邊形'''
# 新建畫板
fig2 = plt.figure()
# 添加子圖
ax3 = fig2.add_subplot(1, 1, 1)
# 畫多邊形
rect = plt.Rectangle((0.1, 0.6), 0.2, 0.3, color='r')  # 矩形 參數:(左下點座標),長,高
circ1 = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.6)  # 橢圓  參數:(橢圓心座標),半徑
circ2 = plt.Circle((0.3, 0.4), 0.1, color='g', alpha=0.6)  # 圓
pgon = plt.Polygon([[0.9, 0.9], [0.7, 0.6], [0.6, 0.8], [0.4, 0.7], [0.5, 0.9]], color='y', alpha=0.7)  # 多邊形,參數:每個頂點的座標
ax3.add_patch(rect)
ax3.add_patch(circ1)
ax3.add_patch(circ2)
ax3.add_patch(pgon)
fig2.canvas.draw()
# 存儲圖像
plt.savefig('G:/demo4.2.png', dpi=200, bbox_inches='tight')
# 顯示畫板
plt.show()
'''
pie()參數:
x       :(每一塊)的比例,如果sum(x) > 1會使用sum(x)歸一化;
labels  :(每一塊)餅圖外側顯示的說明文字;
explode :(每一塊)離開中心距離;
startangle :起始繪製角度,默認圖是從x軸正方向逆時針畫起,如設定=90則從y軸正方向畫起;
shadow  :在餅圖下面畫一個陰影。默認值:False,即不畫陰影;
labeldistance :label標記的繪製位置,相對於半徑的比例,默認值爲1.1, 如<1則繪製在餅圖內側;
autopct :控制餅圖內百分比設置,可以使用format字符串或者format function
        '%1.1f'指小數點前後位數(沒有用空格補齊);
pctdistance :類似於labeldistance,指定autopct的位置刻度,默認值爲0.6;
radius  :控制餅圖半徑,默認值爲1;
counterclock :指定指針方向;布爾值,可選參數,默認爲:True,即逆時針。將值改爲False即可改爲順時針。
wedgeprops :字典類型,可選參數,默認值:None。參數字典傳遞給wedge對象用來畫一個餅圖。例如:wedgeprops={'linewidth':3}設置wedge線寬爲3。
textprops :設置標籤(labels)和比例文字的格式;字典類型,可選參數,默認值爲:None。傳遞給text對象的字典參數。
center :浮點類型的列表,可選參數,默認值:(0,0)。圖標中心位置。
frame :布爾類型,可選參數,默認值:False。如果是true,繪製帶有表的軸框架。
rotatelabels :布爾類型,可選參數,默認爲:False。如果爲True,旋轉每個label到指定的角度。

其中:
colors=['%f' % (i / float(n)) for i in range(n)]
等同於
colors=['0.000000', '0.100000', '0.200000', '0.300000', '0.400000', '0.500000', '0.600000', '0.700000', '0.800000', '0.900000']
'''

五、3D圖

# encoding=utf-8
"""
@Time : 2020/1/11 15:18 
@Author : LiuYanZhe
@File : demo5.py 
@Software: PyCharm
@Description: 3D圖
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 數據
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
# 生成網格數據
X, Y = np.meshgrid(X, Y)
# 計算每個點對的長度
R = np.sqrt(X ** 2 + Y ** 2)
Z = np.sin(R)
'''sin()'''
# 創建畫板
fig = plt.figure()
# 創建子圖
ax = Axes3D(fig)
# 畫3d圖
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)  # rstride:行之間的跨度;cstride:列之間的跨度;camp:顏色映射表
# 設置Z軸維度(區間範圍)
ax.set_zlim(-2, 2)
# 保存圖像
plt.savefig('G:/demo5.1.png', dpi=400, bbox_inches='tight')
'''cos()'''
# 創建畫板
fig2 = plt.figure()
# 創建3d子圖
ax2 = Axes3D(fig2)
# 畫圖
ax2.plot_surface(X, Y, np.cos(R), rstride=1, cstride=1, cmap=plt.cm.coolwarm)  # 畫3d圖
ax2.contourf(X, Y, Z, zdir='z', offset=-2)  # 曲面到底部的投影,zdir:投影到哪個面(x/y/z);offset:表示投影到z=-2
# 設置Z軸維度(區間範圍)
ax2.set_zlim(-2, 2)
# 保存圖像
plt.savefig('G:/demo5.2.png', dpi=400, bbox_inches='tight')
# 顯示圖像
plt.show()

六、盒圖

# encoding=utf-8
"""
@Time : 2020/3/26 11:06 
@Author : LiuYanZhe
@File : Task3.26.py 
@Software: PyCharm
@Description: 盒圖
"""
import numpy as np
import matplotlib.pyplot as plt

data = np.array(
    [13, 15, 16, 16, 19, 20, 20, 21, 22, 22, 25, 25, 25, 25, 30, 33, 33, 35, 35, 35, 35, 36, 40, 45, 46, 52, 70])
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.boxplot(data)
plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章