数据可视化(matplotlib)之plot

折现图

plt.plot官方链接

plt.plot(x, y, ls='-', lw=2, label='plot')

"""
参数说明:
x:x轴上的数值
y: y轴上的数值
ls: 线条风格
ls: 线条宽度
label: 标记图像内容的标签文本
"""

1.基本示例

import matplotlib.pyplot as plt
import numpy as np


x = np.linspace(0.05, 10, 1000)
y = np.cos(x)

plt.plot(x, y, ls='-', lw=2, label='test')
plt.legend()
plt.show()

显示的图像如下所示:
avatar

2.坐标轴设置

在实际的应用过程中往往绘制图像时会注意图像的外观,因此需要对坐标轴进行设置。在matplotlib中可以通过以下的方式进行操作。

  • 设置x轴、y轴数值显示范围

    plt.xlim()、plt.ylim()

  • 设置x轴、y轴的标签文本

    plt.xlabel(), plt.ylabel()

具体代码示例如下:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.05, 10, 1000)
y = np.cos(x)

plt.plot(x, y, c='r', ls='-', lw=2, label='test')
plt.xlim(0.05, 10)
plt.ylim(-1, 1)
plt.xlabel("x_axis")
plt.ylabel("y_axis")
plt.legend()
plt.show()

显示结果:
avatar

图像样式

从上图可以发现x、y轴自动生成的刻度,有时候绘制图像想根据实际需求设置刻度样式,这时就需要定位器(locator)和刻度格式器(formatter).

  • 首先先从ticker导入类 AutoLocator, MultipleLocator, FixedLocator

代码如下:

from matplotlib.ticker import  MultipleLocator, FuncFormatter,AutoMinorLocator

具体代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import  MultipleLocator, FuncFormatter,AutoMinorLocator

## 绘制折线图

x = np.linspace(0.05, 10, 1000)
y = np.cos(x)

fig = plt.figure(figsize=(8, 8))
ax =fig.add_subplot(111)

# ax.xaxis.set_major_locator设置主刻度线位置,MultipleLocator(1.0)相当于单位长度为1的地方设置一个刻度
ax.xaxis.set_major_locator(MultipleLocator(1.0))
ax.yaxis.set_major_locator(MultipleLocator(1.0))

# ax.xaxis.set_minor_locator设置次要刻度线,
# AutoMinorLocator(2)将每个主刻度区间等分成2份

ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))

# set x-minor_tick_formatter
def minor_tick(x, pos):
    if not x % 2.0:
        return ""
    return "%.2f"%x
# 设置好显示位置之后要设置次要刻度线显示位置的精度
# 使用set_minor_formatter()完成,
# 其中参数FuncFormatter(minor_tick)用来控制位置精度

ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))

# change the apperance of ticks and tick labels
# tick_params()用来设置刻度线和刻度标签样式
ax.tick_params("y", which='major',
            length=5, width=2.0,
            color='r')

ax.tick_params(which='minor',
            length=2, width=1.0,
            color='b')
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)

ax.plot(x, y, c='r', ls='-', lw=2, label='test')

ax.grid(linestyle='-', lw=0.5, c='b', zorder=0)
plt.show()

显示结果:

avatar

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值