Python数据可视化matplotlib.pyplot的使用

1.生成数据

  1. 安装matplotlib
    # windows cmd中
    pip install  matplotlib

    在Python环境下,使用import matplotlib检测是否安装成功,不报错就是安装成功;重启写py的工具就可以进行使用了;

  2. 绘制简单图形
    import matplotlib.pyplot as plt
    
    #图形输入值
    input_values = [1,2,3,4,5]
    #图形输出值
    squares = [1,4,9,16,25]
    
    #plot根据列表绘制出有意义的图形,linewidth是图形线宽,可省略
    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)
    #打开matplotlib查看器,并显示绘制图形
    plt.show()

  3.     绘制点
    import matplotlib.pyplot as plt
    
    #绘制散点图(传如一对x和y坐标,在指定位置绘制一个点)
    plt.scatter(2,4)
    #设置输出样式
    plt.scatter(3,5,s=200)
    plt.show()

  4. 绘制一系列的点
import matplotlib.pyplot as plt

x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]

plt.scatter(x_values,y_values,s=100)

plt.show()

       

plot(x,y2,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)

plot(x,y3,color='#900302',marker='+',linestyle='-')

常见的颜色参数:**Colors**

 

    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue 蓝
    ``'g'``          green 绿
    ``'r'``          red 红
    ``'c'``          cyan 蓝绿
    ``'m'``          magenta 洋红
    ``'y'``          yellow 黄
    ``'k'``          black 黑
    ``'w'``          white 白
    =============    ===============================

点型参数**Markers**,如:marker='+' 这个只有简写,英文描述不被识别

 

=============    ===============================
    character        description
    =============    ===============================
    ``'.'``          point marker
    ``','``          pixel marker
    ``'o'``          circle marker
    ``'v'``          triangle_down marker
    ``'^'``          triangle_up marker
    ``'<'``          triangle_left marker
    ``'>'``          triangle_right marker
    ``'1'``          tri_down marker
    ``'2'``          tri_up marker
    ``'3'``          tri_left marker
    ``'4'``          tri_right marker
    ``'s'``          square marker
    ``'p'``          pentagon marker
    ``'*'``          star marker
    ``'h'``          hexagon1 marker
    ``'H'``          hexagon2 marker
    ``'+'``          plus marker
    ``'x'``          x marker
    ``'D'``          diamond marker
    ``'d'``          thin_diamond marker
    ``'|'``          vline marker
    ``'_'``          hline marker
    =============    ===============================

线型参数**Line Styles**,linestyle='-'

    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style 实线
    ``'--'``         dashed line style 虚线
    ``'-.'``         dash-dot line style 点画线
    ``':'``          dotted line style 点线
    =============    ===============================

 

 

 

 

5. 自动计算数据

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=100)

#设置每个坐标轴的取值范围(x轴取值,y轴取值)
plt.axis([0,1100,0,1100000])
plt.show()

      6.删除数据点的轮廓

import matplotlib.pyplot as plt

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

#matplotlib允许你给散点图中的各个点指定颜色。默认为蓝色点和黑色轮廓,在散点图包含的 数据点不多时效果很好。但绘制很多点时,黑色轮廓可能会粘连在一起。
#edgecolor='none'删除数据点的轮廓
plt.scatter(x_values,y_values,edgecolor='none', s=40)


#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
plt.show()

      7.自定义颜色c=''直接传颜色或元组都可以

import matplotlib.pyplot as plt

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

#matplotlib允许你给散点图中的各个点指定颜色。默认为蓝色点和黑色轮廓,在散点图包含的 数据点不多时效果很好。但绘制很多点时,黑色轮廓可能会粘连在一起。
#edgecolor='none'删除数据点的轮廓
plt.scatter(x_values, y_values,c='red', edgecolor='none', s=40)
# plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40)


#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
plt.show()

 

8.使用颜色映射

import matplotlib.pyplot as plt

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

#matplotlib允许你给散点图中的各个点指定颜色。默认为蓝色点和黑色轮廓,在散点图包含的 数据点不多时效果很好。但绘制很多点时,黑色轮廓可能会粘连在一起。
#edgecolor='none'删除数据点的轮廓
plt.scatter(x_values, y_values,c=y_values,cmap=plt.cm.Blues, edgecolor='none', s=40)


#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
plt.show()

将c设置成一个y值列表,并使用参数cmap告诉pyplot使用那个颜色映射,这些代码将y值较小的点显示为浅蓝色,将y值较大的点显示为深蓝色

9.自动保存图表

import matplotlib.pyplot as plt

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

#matplotlib允许你给散点图中的各个点指定颜色。默认为蓝色点和黑色轮廓,在散点图包含的 数据点不多时效果很好。但绘制很多点时,黑色轮廓可能会粘连在一起。
#edgecolor='none'删除数据点的轮廓
plt.scatter(x_values, y_values,c=y_values,cmap=plt.cm.Blues, edgecolor='none', s=40)


#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
# plt.show()
#参数1指定要以什么样的文件名保存图表,保存和代码的同目录下,第二个参数表示要将多余的空白区域剪掉,要保留空白区域,可省略第二个参数
plt.savefig('squares_plot.png',bbox_inches='tight')

 

10. 练习题

动手试一试
15-1 立方:数字的三次方被称为其立方。请绘制一个图形,显示前 5 个整数的立方 值,再绘制一个图形,显示前 5000 个整数的立方值。
15-2 彩色立方:给你前面绘制的立方图指定颜色映射
import matplotlib.pyplot as plt

# #图形输入值
# input_values = [1,2,3,4,5]
# #图形输出值
# square = [1,8,27,64,125]

# plt.scatter(input_values,square,linewidth = 5)

# plt.title("cube",fontsize = 24)
# plt.show()


input_values = list(range(0,5000))

square = [x**3 for x in input_values]

plt.scatter(input_values,square,c=input_values,cmap=plt.cm.Reds,edgecolor='none',s=40);
plt.show()

11.随机漫步(绘制随机漫步图)

from random import choice

class RandomWalk(object):
    """一个生成随机漫步数据的类"""
    def __init__(self, num_points = 5000):
        """初始化随机漫步的属性"""
        #存储随机漫步次数的变量
        self.num_points = num_points
        #所有随机漫步都始于(0,0)
        #分别存储随机漫步经过的每个点的x和y坐标
        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

            #拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue

            #计算下一个点的x值和y值
            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)
        pass

绘制随机漫步图

import matplotlib.pyplot as plt

from random_walk import RandomWalk


#创建一个RandomWalk实例,并将其包含的点都绘制出来

rw = RandomWalk()

rw.fill_walk()

plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()

12.模拟多次随机漫步

import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序处于活动状态,就不断的模拟漫步

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()

    plt.scatter(rw.x_values,rw.y_values,s=15)
    plt.show()
    
    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

13.给点着色

import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序处于活动状态,就不断的模拟漫步

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolor='none',s=15)
    plt.show()
    
    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

14.重

新绘制起点和终点

import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序处于活动状态,就不断的模拟漫步

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
    
    #突出起点和终点
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    plt.show()

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

15. 隐藏坐标轴

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk()
    rw.fill_walk()

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=15)
    
    #突出起点和终点
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',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

16. 增加点数(增加点数,将每个点的大小调小)

 

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)
    
    #突出起点和终点
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',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

17. 调整尺寸以适应屏幕

while True:
    #创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(50000)
    rw.fill_walk()

    #设置绘图窗口的尺寸
    #figure()用于指定图表的宽度,高度,分辨率黑背景色figsize需要指定一个元组,单位英寸,dpi是分辨率,可传可不传
    plt.figure(dpi=128,figsize=(10,6))

    point_numbers = list(range(rw.num_points))

    plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)
    
    #突出起点和终点
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',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

18.练习1

分子运动:修改 rw_visual.py,将其中的 plt.scatter()替换为 plt.plot()。为 模拟花粉在水滴表面的运动路径,向 plt.plot()传递 rw.x_values 和 rw.y_values,并 指定实参值 linewidth。使用 5000 个点而不是 50 000 个点。

作者:Dover杨
链接:https://www.jianshu.com/p/85a01b7d6507
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

改进的随机漫步:在类 RandomWalk 中,x_step 和 y_step 是根据相同的条件生 8
成的:从列表[1, -1]中随机地选择方向,并从列表[0, 1, 2, 3, 4]中随机地选择距离。 请修改这些列表中的值,看看对随机漫步路径有何影响。尝试使用更长的距离选择列表, 如 0~8;或者将1 从 x 或 y 方向列表中删除。



    def fill_walk(self):
        """计算随机漫步包含的所有点"""

        #不断漫步,直到列表达到指定的长度
        while len(self.x_values) < self.num_points:
            #决定前进方向以及沿这个方向前进的距离
            x_direction = choice([1])
            x_distance = choice([0,1,2,3,4,5,6,7,8])
            x_step = x_direction * x_distance
            
            y_direction = choice([1])
            y_distance = choice([0,1,2,3,4,5,6,7,8])
            y_step = y_direction * y_distance

            #拒绝原地踏步
            if x_step == 0 and y_step == 0:
                continue

            #计算下一个点的x值和y值
            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)
        pass

 

 

文章源出处:https://www.jianshu.com/p/85a01b7d6507

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值