python學習------matplotlib

繪製折線圖

import matplotlib.pyplot as plt

square = [1, 4, 9, 16, 25]
input_square = [1, 2, 3, 4, 5]

# 同時傳入x,y座標
plt.plot(input_square, square, linewidth=5, color='red')
plt.title("Square Numbers", fontsize=14)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 設置刻度標記的大小
plt.tick_params(axis='both', labelsize=14)
plt.show()

在這裏插入圖片描述

figure

可以設置圖的名稱num、圖的大小figuresize和dpi

import numpy as np
import matplotlib.pyplot as plt


if __name__ == '__main__':
    x = np.linspace(-3, 3, num=50)
    y1 = x**2
    y2 = x + 1

    # 每一個figure對應一個輸出圖, 圖的名稱爲figure $num
    plt.figure(figsize=(8, 5), num=2)
    plt.plot(x, y1)

    # 設置線條的形狀
    plt.plot(x, y2, color='red', linewidth=3, linestyle='--')
    plt.show()

在這裏插入圖片描述

設置座標軸刻度

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')

# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()

在這裏插入圖片描述

設置座標軸位置

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')

# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# gca = 'get current axis',將當前的圖形賦值給ax
ax = plt.gca()

# 消除頂部和右部
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# 分別將x,y座標賦值給ax底部和左部
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# 調整x, y軸的位置
ax.spines['bottom'].set_position(('data', 0)) # outward, axes
ax.spines['left'].set_position(('data', 0))
plt.show()

在這裏插入圖片描述

legend

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()

# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')

# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# 設置標籤
l1, = plt.plot(x, y2, label='line1')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='line2')

'''loc字段
best, upper right, upper left, lower left, lower right, right
center left, center right, lower center, upper center, center'''
# legend中的label會覆蓋handles中的圖形label
plt.legend(handles=[l1, l2], labels=['aaa', 'bbb'], loc='lower right')
plt.show()

在這裏插入圖片描述

annotation標註

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))

x0 = 1
y0 = 2*x0 + 1

# k代表black,k--代表黑色+樣式爲虛線--
plt.scatter(x0, y0, color='k')
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)
plt.plot([0, x0], [y0, y0], 'k--', lw=2.5)

# 圖形中添加註釋1
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text.\ \mu\ \sigma_i\ \alpha$',
         fontdict={'size': 16, 'color': 'r'})

# 圖形中添加註釋2
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
             fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))
plt.show()


在這裏插入圖片描述

繪製散點圖

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]

# s表示size,默認爲藍色點和無輪廓,c爲點的顏色(可以使用rgb色),edgecolors爲數據點輪廓
plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolors='none', s=40)
plt.title("Square Number")
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# 設置每個座標軸的取值範圍
plt.axis([0, 100, 0, 11000])
plt.show()

# s表示size,默認爲藍色點和無輪廓,按照y軸方向設置漸變色
# 奇怪的是顯示效果不明顯
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds, edgecolors='none', s=40)
# 保存路徑,是否剪掉空白區域
plt.savefig('squares_plot.png', bbox_inches='tight')

在這裏插入圖片描述

隨機漫步

import matplotlib.pyplot as plt
from random import choice

class RandomWalk():
    # 一共要走步數: num_points
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_dire = choice([1, -1])
            x_dis = choice([1, 2, 3, 4])
            x_step = x_dire * x_dis
            y_dire = choice([1, -1])
            y_dis = choice([1, 2, 3, 4])
            y_step = y_dire * y_dis

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)

walk = RandomWalk()
walk.fill_walk()
plt.title("RandomWalkTrack",fontsize=16)
plt.xlabel("x", fontsize=14)
plt.ylabel("y", fontsize=14)
plt.scatter(walk.x_values, walk.y_values, s=20)
plt.savefig("E://random_walk.png")
plt.show()

在這裏插入圖片描述

漸變

plt.scatter(walk.x_values, walk.y_values, c=list(range(walk.num_points)), cmap=plt.cm.Blues, edgecolors='none', s=40)

隱藏座標軸

# 隱藏座標軸
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

起始位置和終點位置標記

# 隱藏座標軸
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(walk.x_values[-1], walk.y_values[-1], c='red', edgecolors='none', s=100)

在這裏插入圖片描述








發佈了59 篇原創文章 · 獲贊 12 · 訪問量 9651
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章