数据分析2之数据可视化

1.matplotlib基本使用

import numpy as np
import matplotlib.pyplot as plt

# y=x**2绘制
x_arr = np.arange(9)
y_arr = x_arr**2
plt.plot(x_arr, y_arr)

# 绘制水平线
plt.hlines(30, 2, 7, colors='red')
# 绘制垂直线
# plt.vlines(3, 10, 50, colors='yellow')
plt.vlines([2, 3, 4, 5], [10, 20, 30, 40], [20, 30, 40, 50], colors='blue')
plt.show()

# 绘制y=sin(x)
x_arr = np.linspace(-np.pi, np.pi, 1000)                    # 线性拆分
y_arr = np.sin(x_arr)
plt.plot(x_arr, y_arr)
# 绘制坐标抽范围
plt.xlim(-np.pi, np.pi)
plt.ylim(-1, 1)
plt.show()

import numpy as np
import matplotlib.pyplot as plt

"""
linestyle:线样式 '-','--','-.',':'
linewidth:线宽 数字
color:颜色 (r,g,b) #ffffff (r,g,b,alpha)
alpha:透明度
"""

x_arr = np.linspace(-np.pi, np.pi, 1000)                    # 线性拆分
y_arr = np.cos(x_arr)
plt.plot(x_arr, y_arr)
# 设置坐标刻度
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$'])
plt.yticks([-1, -1/2, 0, 1/2, 1])

# 设置坐标轴
ax = plt.gca()
ax_l = ax.spines['left']
ax_b = ax.spines['bottom']
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax_l.set_position(('data', 0))
ax_b.set_position(('data', 0))
plt.show()

 

import numpy as np
import matplotlib.pyplot as plt

x_arr = np.linspace(-np.pi, np.pi, 1000)                    # 线性拆分
sinx = np.sin(x_arr)
cosx = np.cos(x_arr)
plt.plot(x_arr, sinx, label=r'$y=sin(x)$')
plt.plot(x_arr, cosx, label=r'$y=cos(x)$')
# 设置坐标刻度
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$'])
plt.yticks([-1, -1/2, 0, 1/2, 1])
# 设置坐标轴
ax = plt.gca()
ax_l = ax.spines['left']
ax_b = ax.spines['bottom']
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax_l.set_position(('data', 0))
ax_b.set_position(('data', 0))

# 绘制特殊点
px = [np.pi/2, np.pi/2]
py = [1, 0]
plt.scatter(px, py, marker='o', s=100, edgecolors='red', facecolor='green')

"""
           marker='', 		#点型 ~ matplotlib.markers
           s='', 			#大小
           edgecolor='', 	#边缘色
           facecolor='',	#填充色
           zorder=3			#绘制图层编号 (编号越大,图层越靠上)
"""

# 备注,特殊点的信息

plt.annotate(
    r'$[\frac{\pi}{2},1]$',	# 备注中显示的文本内容
    xycoords='data',	        # 备注目标点所使用的坐标系(data表示数据坐标系)
    xy=(px[0], py[0]),	 	# 备注目标点的坐标
    textcoords='offset points',	    # 备注文本所使用的坐标系(offset points表示参照点的偏移坐标系)
    xytext=(px[0]+40, py[0]+40),	 # 备注文本的坐标
    fontsize=14,			# 备注文本的字体大小
    arrowprops=dict()			# 使用字典定义文本指向目标点的箭头样式
)
# 图例
plt.legend()             # 需要设置label
plt.show()

import matplotlib.pyplot as plt
import numpy as np

# 窗口设置
plt.figure(
    'figure-1',                    # 标题设置
    facecolor='grey'
)
plt.plot([1, 2], [3, 4])
plt.figure(
    'figure-2',
    facecolor='lightgrey'
)
plt.title('salary')           # 图标题
plt.xlabel('x')               # x轴
plt.ylabel('y')
plt.grid(linestyle='-')       # 设置网格线
plt.tight_layout()            # 重新布局图
plt.plot([1, 2], [4, 3])
# 重新调用窗口
plt.figure('figure-1')
plt.show()


# 子图
# 矩阵布局
plt.figure('Subplot Layout', facecolor='lightgray')
for i in range(9):
    plt.subplot(3, 3, i+1)
    plt.text(
        0.5, 0.5, i+1,
        size=36,
        ha='center',
        va='center',
        color='red'
    )
    plt.xticks([])           # 取消刻度
    plt.yticks([])
plt.tight_layout()
plt.show()

# 网格布局,支持合并
import matplotlib.gridspec as mg
plt.figure('Subplot Layout', facecolor='lightgray')
gs = mg.GridSpec(3, 3)
plt.subplot(gs[0, :2])
plt.text(0.5, 0.5, '1', ha='center', va='center', size=36)
plt.xticks([])
plt.yticks([])
plt.tight_layout()

plt.subplot(gs[:2, 2])
plt.text(0.5, 0.5, '2', ha='center', va='center', size=36)
plt.xticks([])
plt.yticks([])
plt.tight_layout()

plt.subplot(gs[1:, 0])
plt.text(0.5, 0.5, '3', ha='center', va='center', size=36)
plt.xticks([])
plt.yticks([])
plt.tight_layout()

plt.subplot(gs[2, 1:])
plt.text(0.5, 0.5, '4', ha='center', va='center', size=36)
plt.xticks([])
plt.yticks([])
plt.tight_layout()

plt.subplot(gs[1, 1])
plt.text(0.5, 0.5, '5', ha='center', va='center', size=36)
plt.xticks([])
plt.yticks([])
plt.tight_layout()
plt.show()

# 自由布局
plt.figure('FlowLayout', facecolor='lightgray')

plt.axes([0.03, 0.03, 0.94, 0.46])
plt.text(0.5, 0.5, 1, ha='center', va='center', size=36)
plt.axes([0.03, 0.50, 0.94, 0.46])
plt.text(0.5, 0.5, 2, ha='center', va='center', size=36)
plt.show()

# 刻度定位器
plt.figure('locator', facecolor='lightgrey')
ax = plt.gca()
# 隐藏除底轴以外的所有坐标轴
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.yticks([])
plt.xlim(0, 10)
# 将底坐标轴调整到子图中心位置
ax.spines['bottom'].set_position(('data', 0.5))
# 设置水平坐标轴的主刻度定位器NullLocator():不显示刻度
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
# 设置水平坐标轴的次刻度定位器为多点定位器,间隔0.1
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))

plt.show()

# 循环使用刻度定位器
locators = ['plt.NullLocator()', 'plt.MaxNLocator(nbins=4)', 'plt.LogLocator(base=2)']

for i, locator in enumerate(locators):
    plt.subplot(len(locators), 1, i + 1)
    plt.xlim(0, 10)
    plt.ylim(-1, 1)
    plt.yticks([])
    # 获取当前坐标轴
    ax = plt.gca()
    # 绘制刻度网格线
    ax.grid(
        which='major',  # 'major'/'minor' <-> '主刻度'/'次刻度'
        axis='x',  # 'x'/'y'/'both' <-> 绘制x或y轴
        linewidth=1,  # 线宽
        linestyle='--',  # 线型
        color='blue',  # 颜色
        alpha=0.5  # 透明度
    )
    # 隐藏除底轴以外的所有坐标轴
    ax.spines['left'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    # 将底坐标轴调整到子图中心位置
    ax.spines['bottom'].set_position(('data', 0))
    # 设置水平坐标轴的主刻度定位器
    ax.xaxis.set_major_locator(eval(locator))
    # 设置水平坐标轴的次刻度定位器为多点定位器,间隔0.1
    ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))
    plt.plot(np.arange(11), np.zeros(11), c='none')
    # 标记所用刻度定位器类名
    plt.text(5, 0.3, locator, ha='center', size=12)

plt.show()

import numpy as np
import matplotlib.pyplot as plt

# 散点图
plt.title('point chart', fontsize=18)
x = np.random.normal(175, 20, 300)
y = np.random.normal(65, 10, 300)
d = np.sqrt((x-175)**2+(y-65)**2)       # 欧拉距离
plt.scatter(
    x, y,
    marker='o',
    s=10,
    c=d,               # 按距离设置颜色,数越小越蓝,越大越红
    cmap='jet',        # 颜色映射方式
    label='points'
)
plt.xlabel('height')
plt.ylabel('weight')
# plt.legend()
plt.show()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值