【python】Matplotlib作图小结

Matplotlib tutorials: https://matplotlib.org/tutorials/index.html

基础作图

Matplotib Usage Guide: 这个教程包含Matplotlib最基础的使用方式

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100)

# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots()  # Create a figure and an axes.
ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.set_xlabel('x label')  # Add an x-label to the axes.
ax.set_ylabel('y label')  # Add a y-label to the axes.
ax.set_title("Simple Plot")  # Add a title to the axes.
ax.legend()  # Add a legend.
plt.show()

图示结果:

调整图中字体的大小和格式

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2, 100)

fig, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')

#设置坐标刻度值的大小以及刻度值的字体
plt.tick_params(labelsize=12)
labels = ax.get_xticklabels() + ax.get_yticklabels()
[label.set_fontname('Times New Roman') for label in labels]

# 设置横纵坐标的名称以及对应字体格式
font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 14,
}
plt.xlabel("x label", font1)
plt.ylabel("y label", font1)


#设置图例并且设置图例的字体及大小
font2 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 12,
}
ax.legend(loc='best', prop=font2)
plt.savefig('figure.png', dpi=300)
plt.show()

图示结果:
在这里插入图片描述

科学计数法


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 100, 100)
fig, ax = plt.subplots(1, 1)
ax.plot(x, x**2)
ax.set(xlabel='x', ylabel='x^2',
       title='scientific notation')

# scientific notation
from matplotlib import ticker
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-1,1))
ax.yaxis.set_major_formatter(formatter) # for y axis
ax.xaxis.set_major_formatter(formatter) # for x axis

ax.grid()
fig.savefig("test.png", dpi=300)
plt.show()

图示结果:
在这里插入图片描述

关于无法显示图像的问题

有时使用matplotlib 中的plt.imshow(img)和plt.show()后无法正常显示图像,此时可以检查matplotlib的backend采用的版本matplotlib.get_backend()发现是‘agg’的方式,然后修改backend的版本matplotlib.use(‘TkAgg’) 即可显示图像。

“matplotlib.use(‘agg‘)“语句的作用机理

参考

CSDN博客《python matplotlib 画图刻度、图例等字体、字体大小、刻度密度、线条样式设置
CSDN博客《matplotlib命令与格式:图例legend语法及设置

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值