最近全面地从 MATLAB 转向 Python 了,而 matplotlib 是 Python 主要的画图包。这篇日志记录一些日常使用 matplotlib 的 tips.

How to save a figure remotely with pylab?

如果是在 AWS 或者学校的服务器上跑程序,这是一定会遇上的问题。本质原因是

By default, matplotlib will use something like the TkAgg backend. This requires an X-server to be running.

而我们的 Server 上又是没有 X-server 的,所以程序就会报错,解决方法也简单,就是 use the Agg backend instead.

1
2
3
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import matplotlib.pyplot as plt

绘制双 Y 轴曲线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import matplotlib.pyplot as plt
import numpy as np


mAPs = [0.182, 0.278, 0.428, 0.456, 0.283, 0.483, 0.484, 0.529, 0.503, 0.349, \
0.487, 0.553, 0.592, 0.469, 0.427, 0.504, 0.516, 0.561, 0.506, 0.531, \
0.456, 0.489, 0.520, 0.503, 0.578, 0.527, 0.550, 0.457, 0.504, 0.516]
mAPs = np.array(mAPs)

losses = [14.3, 12.7, 12.5, 10.4, 9.25, 9.99, 8.60, 10.4, 10.8, 8.43, \
7.90, 8.50, 999, 9.00, 9.07, 8.19, 8.55, 8.07, 11.2, 8.89, \
7.40, 6.16, 1180, 6.24, 9.77, 6.46, 1170, 10.4, 5.56, 6.09]
losses = np.array(losses)

epoch = np.array(list(range(30)))

fig = plt.figure()

ax1 = fig.add_subplot(111)
ax1.plot(epoch, mAPs)
ax1.set_ylabel("mAP")

ax2 = ax1.twinx()
ax2.plot(epoch, losses, 'r')
ax2.set_ylim([0,30])

plt.show()

最关键的就是 ax2 = ax1.twinx() 这一句。


如果您觉得我的文章对您有所帮助,不妨小额捐助一下,您的鼓励是我长期坚持的一大动力。

Alipay_Middle Wechat_Middle