matplotlib简单使用
生活大爆炸

matplotlib简单使用

hualala
2021-12-30 / 0 评论 / 1,271 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年01月08日,已超过831天没有更新,若内容或图片失效,请留言反馈。

[hide]

绘制二维散点图

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3])
y = np.array([1,2,3])

plt.figure()
plt.scatter(x, y, c='r', marker='^', label='point')

# 绘制图例
plt.legend(loc=1, bbox_to_anchor=(1.0, 1.0))
# 限制x轴坐标长度
plt.xlim(right=5)

# 展示
plt.show()

绘制三维散点图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # 空间三维画图

x = np.array([1,2,3])
y = np.array([1,2,3])
z = np.array([1,2,3])

# 绘制散点图
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='^', label='坐标点')

# 绘制图例,调整图例位置
ax.legend(loc='best', bbox_to_anchor=(1.2, 1.0))

# 添加坐标轴(顺序是Z, Y, X)
ax.set_zlabel('Z', fontdict={'size': 8, 'color': 'red'})
ax.set_ylabel('Y', fontdict={'size': 8, 'color': 'green'})
ax.set_xlabel('X', fontdict={'size': 8, 'color': 'blue'})

# 展示
plt.show()

scatter参数说明:


参数c 可以等于:['c', 'b', 'g', 'r', 'm', 'y', 'k', 'w']

  • b——blue
  • c——cyan
  • g——green
  • k——black
  • m——magenta
  • r——red
  • w——white
  • y——yellow
    图例位置(对应参数loc)


    还想再调整,可以使用参数bbox_to_anchor=(1.3, 1.0)

每个点加标签

两种方式可以实现:

  • text: 称为无指向型标注,标注仅仅包含注释的文本内容;
  • annotate: 称为指向型注释,标注不仅包含注释的文本内容还包含箭头指向,能够突显细节;

text方式:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
plt.text(0, 0.75, r'max', fontdict = {
'family': 'Times New Roman', # 标注文本字体
'fontsize': 20, # 文本大小
'fontweight': 'bold', # 字体粗细
'fontstyle': 'italic', # 字体风格
'color': 'red',  # 文本颜色
'backgroundcolor': 'blue', # 背景颜色
'bbox': {'boxstyle':'round'} # 椭圆外框
})

plt.text(-3, 0.75, r'$cos(x)$',
family = 'Times New Roman', # 标注文本字体
fontsize = 18, # 文本大小
fontweight = 'bold', # 字体粗细
color = 'green' # 文本颜色
)
plt.plot(-3, 0.75, 'x', color = 'r')
plt.show()

annotate方式:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 300)
y = np.cos(x)
plt.plot(x, y)
plt.annotate(r'$max$', xy = (0, 1), xytext = (0, 0.75),
arrowprops = {
'headwidth': 10, # 箭头头部的宽度
'headlength': 5, # 箭头头部的长度
'width': 4, # 箭头尾部的宽度
'facecolor': 'r', # 箭头的颜色
'shrink': 0.1, # 从箭尾到标注文本内容开始两端空隙长度
},
family='Times New Roman',  # 标注文本字体为Times New Roman
fontsize=18,  # 文本大小为18
fontweight='bold',  # 文本为粗体
color='green',  # 文本颜色为红色
# ha = 'center' # 水平居中
)

plt.plot(0, 1, 'x', color = 'r')
plt.plot(0, 0.75, 'x', color = 'r')

plt.show()

坐标取消科学计数法

matplotlib.rcParams["axes.formatter.useoffset"] = False

以下尝试都无效:

x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
x_formatter.set_scientific(False)
ax.xaxis.set_major_formatter(x_formatter)
ax.yaxis.set_major_formatter(x_formatter)
# --------------------------------- #
ax.get_xaxis().get_major_formatter().set_scientific(False)
ax.get_yaxis().get_major_formatter().set_scientific(False)
# --------------------------------- #
ax.ticklabel_format(style='plain')

[/hide]

0

评论 (0)

取消