python之数据可视化方案

数据可视化

matplotlib

matplotlib是python的一个绘图库。使用它可以很方便的绘制出版质量级别的图形。

matplotlib基本功能

  1. 基本绘图 (在二维平面坐标系中绘制连续的线)

    1. 设置线型、线宽和颜色

    2. 设置坐标轴范围

    3. 设置坐标刻度

    4. 设置坐标轴

    5. 图例

    6. 特殊点

    7. 备注

  2. 图形对象(图形窗口)

    1. 子图

    2. 刻度定位器

    3. 刻度网格线

    4. 半对数坐标

    5. 散点图

    6. 填充

    7. 条形图

    8. 饼图

    9. 等高线图

    10. 热成像图

    11. 三维曲面

    12. 简单动画

 

matplotlib基本功能详解

基本绘图

1)绘图核心API

案例: 绘制简单直线

 

import numpy as np
import matplotlib.pyplot as plt
​
# 绘制简单直线
x = np.array([1, 2, 3, 4, 5])
y = np.array([3, 6, 9, 12, 15])
​
# 绘制水平线、垂线
plt.axhline(y=6, ls=":", c="blue")  # 添加水平直线
plt.axvline(x=4, ls="-", c="red")  # 添加垂直直线
​
# 绘制多段垂线
plt.vlines([2, 3, 3.5],  # 垂线的x坐标值
           [10, 20, 30],  # 每条垂线起始y坐标
           [25, 35, 45])  # 每条垂线结束y坐标
​
plt.plot(x, y)
plt.show() # 显示图片,阻塞方法

 

2)设置线型、线宽

 

linestyle: 设置线型,常见取值有实线('-')、虚线('--')、点虚线('-.')、点线(':')

linewidth:线宽

color:颜色

颜色的英文单词:red, blue, green等
颜色的英文缩写:r, b, g
元组:(0.3, 0.4, 0.5)   (r, g, b)
     (0.3, 0.3, 0.6, 0.3)  最后一位是透明度
字符串:#aabbcc

alpha: 设置透明度(0~1之间)

案例:绘制正弦、余弦曲线,并设置线型、线宽、颜色、透明度

# 绘制正弦曲线
import numpy as np
import matplotlib.pyplot as plt
import math
​
x = np.arange(0, 2 * np.pi, 0.1)  # 以0.1为单位,生成0~6的数据
print(x)
y1 = np.sin(x)
y2 = np.cos(x)
​
# 绘制图形
plt.plot(x, y1, label="sin", linewidth=2)  # 实线,线宽2像素
plt.plot(x, y2, label="cos", linestyle="--", linewidth=4)  # 虚线,线宽4像素
​
plt.xlabel("x")  # x轴文字
plt.ylabel("y")  # y轴文字
​
# 设置坐标轴范围
plt.xlim(0, 2 * math.pi)
plt.ylim(-1, 2)
​
plt.title("sin & cos")  # 图标题
plt.legend()  # 图例
plt.show()

 

3)设置坐标轴范围

语法:

#x_limt_min:    <float> x轴范围最小值
#x_limit_max:   <float> x轴范围最大值
plt.xlim(x_limt_min, x_limit_max)
#y_limt_min:    <float> y轴范围最小值
#y_limit_max:   <float> y轴范围最大值
plt.ylim(y_limt_min, y_limit_max)

4)设置坐标刻度

 

语法:

#x_val_list:    x轴刻度值序列
#x_text_list:   x轴刻度标签文本序列 [可选]
plt.xticks(x_val_list , x_text_list )
#y_val_list:    y轴刻度值序列
#y_text_list:   y轴刻度标签文本序列 [可选]
plt.yticks(y_val_list , y_text_list )

案例:绘制二次函数曲线

# 绘制二次函数曲线
import numpy as np
import matplotlib.pyplot as plt
import math
​
x = np.arange(-5, 5, 0.1)  # 以0.1为单位,生成-5~5的数据
print(x)
y = x ** 2
​
# 绘制图形
plt.plot(x, y, label="$y = x ^ 2$",
         linewidth=2,  # 线宽2像素
         color="red",  # 颜色
         alpha=0.5)  # 透明度
​
plt.xlabel("x")  # x轴文字
plt.ylabel("y")  # y轴文字
​
# 设置坐标轴范围
plt.xlim(-10, 10)
plt.ylim(-1, 30)
​
# 设置刻度
x_tck = np.arange(-10, 10, 2)
x_txt = x_tck.astype("U")
plt.xticks(x_tck, x_txt)
​
y_tck = np.arange(-1, 30, 5)
y_txt = y_tck.astype("U")
plt.yticks(y_tck, y_txt)
​
plt.title("square")  # 图标题
plt.legend(loc="upper right")  # 图例 upper right, center
plt.show()

 

刻度文本的特殊语法 -- LaTex排版语法字符串

r'$x^n+y^n=z^n$',   r'$\int\frac{1}{x} dx = \ln |x| + C$',     r'$-\frac{\pi}{2}$'

5)设置坐标轴

 

 

坐标轴名:left / right / bottom / top

# 获取当前坐标轴字典,{'left':左轴,'right':右轴,'bottom':下轴,'top':上轴 }
ax = plt.gca()
# 获取其中某个坐标轴
axis = ax.spines['坐标轴名']
# 设置坐标轴的位置。 该方法需要传入2个元素的元组作为参数
# type: <str> 移动坐标轴的参照类型  一般为'data' (以数据的值作为移动参照值)
# val:  参照值
axis.set_position((type, val))
# 设置坐标轴的颜色
# color: <str> 颜色值字符串
axis.set_color(color)

案例:设置坐标轴格式

# 设置坐标轴
import matplotlib.pyplot as plt
​
ax = plt.gca()
axis_b = ax.spines['bottom']  # 获取下轴
axis_b.set_position(('data', 0))  # 设置下轴位置, 以数据作为参照值
​
axis_l = ax.spines['left']  # 获取左轴
axis_l.set_position(('data', 0))  # 设置左轴位置, 以数据作为参照值
​
ax.spines['top'].set_color('none')  # 设置顶部轴无色
ax.spines['right'].set_color('none')  # 设置右部轴无色
​
plt.show()

 

6)图例

显示两条曲线的图例,并测试loc属性。

# 再绘制曲线时定义曲线的label
# label: <关键字参数 str> 支持LaTex排版语法字符串
plt.plot(xarray, yarray ... label='', ...)
# 设置图例的位置
# loc: <关键字参数> 制定图例的显示位置 (若不设置loc,则显示默认位置)
#    ===============   =============
#    Location String   Location Code
#    ===============   =============
#    'best'            0
#    'upper right'     1
#    'upper left'      2
#    'lower left'      3
#    'lower right'     4
#    'right'           5
#    'center left'     6
#    'center right'    7
#    'lower center'    8
#    'upper center'    9
#    'center'          10
#    ===============   =============
plt.legend(loc='')

7)特殊点

 

语法:

# xarray: <序列> 所有需要标注点的水平坐标组成的序列
# yarray: <序列> 所有需要标注点的垂直坐标组成的序列
plt.scatter(xarray, yarray, 
           marker='',       #点型 ~ matplotlib.markers
           s='',            #大小
           edgecolor='',    #边缘色
           facecolor='',    #填充色
           zorder=3         #绘制图层编号 (编号越大,图层越靠上)
)
​

示例:在二次函数图像中添加特殊点

# 绘制特殊点
plt.scatter(x_tck,  # x坐标数组
            x_tck ** 2,  # y坐标数组
            marker="s",  # 点形状 s:square
            s=40,  # 大小
            facecolor="blue",  # 填充色
            zorder=3)  # 图层编号

 

marker点型可参照:help(matplotlib.markers)

也可参照附录: matplotlib point样式

 

8)备注

 

语法:

# 在图表中为某个点添加备注。包含备注文本,备注箭头等图像的设置。
plt.annotate(
    r'$\frac{\pi}{2}$',         #备注中显示的文本内容
    xycoords='data',            #备注目标点所使用的坐标系(data表示数据坐标系)
    xy=(x, y),                  #备注目标点的坐标
    textcoords='offset points', #备注文本所使用的坐标系(offset points表示参照点的偏移坐标系)
    xytext=(x, y),              #备注文本的坐标
    fontsize=14,                #备注文本的字体大小
    arrowprops=dict()           #使用字典定义文本指向目标点的箭头样式
)

arrowprops参数使用字典定义指向目标点的箭头样式

#arrowprops字典参数的常用key
arrowprops=dict(
    arrowstyle='',      #定义箭头样式
    connectionstyle=''  #定义连接线的样式
)
​

箭头样式(arrowstyle)字符串如下

============   =============================================
Name           Attrs
============   =============================================
  '-'          None
  '->'         head_length=0.4,head_width=0.2
  '-['         widthB=1.0,lengthB=0.2,angleB=None
  '|-|'        widthA=1.0,widthB=1.0
  '-|>'        head_length=0.4,head_width=0.2
  '<-'         head_length=0.4,head_width=0.2
  '<->'        head_length=0.4,head_width=0.2
  '<|-'        head_length=0.4,head_width=0.2
  '<|-|>'      head_length=0.4,head_width=0.2
  'fancy'      head_length=0.4,head_width=0.4,tail_width=0.4
  'simple'     head_length=0.5,head_width=0.5,tail_width=0.2
  'wedge'      tail_width=0.3,shrink_factor=0.5
============   =============================================
​
​

连接线样式(connectionstyle)字符串如下

============   =============================================
Name           Attrs
============   =============================================
  'angle'       angleA=90,angleB=0,rad=0.0
  'angle3'      angleA=90,angleB=0`   
  'arc'         angleA=0,angleB=0,armA=None,armB=None,rad=0.0
  'arc3'        rad=0.0
  'bar'         armA=0.0,armB=0.0,fraction=0.3,angle=None
============   =============================================
​
​
​

示例:在二次函数图像中添加备注

# 设置备注
plt.annotate(
    r'$y = x ^ 2$',         #备注中显示的文本内容
    xycoords='data',            #备注目标点所使用的坐标系(data表示数据坐标系)
    xy=(4, 16),                 #备注目标点的坐标 (4,16)
    textcoords='offset points', #备注文本所使用的坐标系(offset points表示参照点的偏移坐标系)
    xytext=(20, 30),                #备注文本的坐标
    fontsize=14,                #备注文本的字体大小
    arrowprops=dict(
        arrowstyle="->", connectionstyle="angle3"
    )           #使用字典定义文本指向目标点的箭头样式
)

 

####

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深耕AI

谢谢鼓励~我将继续创作优质博文

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值