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)

在这里插入图片描述








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值