Python3:项目可视化(Matplotlib)

1.简单的入门使用plot()

#mpl_squares.py
import matplotlib.pyplot as plt

input_values=[1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values,squares,linewidth=5)
plt.title('Square Numbers',fontsize=24)
plt.xlabel('Value',fontsize=14)
plt.ylabel('Square of Value',fontsize=14)
plt.tick_params(axis='both',labelsize=14)
plt.show()

 

2.然后绘制散点图scatter()

#scatter_squares.py
import matplotlib.pyplot as plt

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

plt.scatter(x_values,y_values,s=40,edgecolors='none',c=y_values,cmap=plt.cm.Reds) #c=(R,G,B)
plt.axis([0,1100,0,1100000])
plt.title('Squares Numbers',fontsize=24)
plt.xlabel('Value',fontsize=14)
plt.ylabel('Square of Value',fontsize=14)
plt.tick_params(axis='both',which='major',labelsize=14)
plt.savefig('squares_plot.png',bbox_inches='tight')
#savefig存储图片,第一个参数存储路径,第二个实参指定将图表多余的空白区域剪裁掉,如果要保留图表多余的空白区域,可以省略这个参数

这里使用了颜色映射(colormap)是一系列颜色,它们从起始颜色渐变到结束颜色。例如,较浅的颜色来显示较小的值,较深的颜色来显示较大的值。

1.c=y轴列表

2.cmp告诉pyplot使用哪个颜色映射。

此外,scatter.py中使用savefig()来代替show(),它可以自动保存图表

 

3.随机漫步

#random_walk
from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
    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_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance

            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance
            #y_step = choice(range(-4,5))

            #拒绝原地踏步
            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)

if __name__ == '__main__':
    while True:
        rw = RandomWalk(50000)
        rw.fill_walk()
        plt.scatter(rw.x_values,rw.y_values,s=1,c=list(range(rw.num_points)),cmap=plt.cm.Reds,edgecolors='none')

        #突出起点和终点
        plt.scatter(0,0,c='green',edgecolors='none',s=100)
        plt.scatter(rw.x_values[-1], rw.y_values[-1], c='blue', edgecolors='none', s=100)

        #隐藏坐标轴
        plt.axes().get_xaxis().set_visible(False)
        plt.axes().get_yaxis().set_visible(False)

        plt.show()

        keep_running = input('Make another walk? (y/n):')
        if keep_running == 'n':
            break

 

参考文献:

[1] Python编程从入门到实践284-303

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值