2 回答
TA贡献1784条经验 获得超8个赞
这是对齐它们的一种方法。思路如下:
首先使用 ( ax1)在下 x 轴上绘制数据
然后使用设置上 x 轴的限制与下 x 轴相同 ax3.set_xlim(ax1.get_xlim())
然后在对应于下 x 轴值 (10, 20, 30, ..., 90, 100) 的位置设置上 x 轴的刻度
最后,使用 重命名刻度标签ax3.set_xticklabels()。
这是代码:我正在用注释替换代码中已有的部分#。
# imports and define data and compute accuracy and loss here
# Initiate figure and axis objects here
ax1.set_xlabel('batches')
ax1.set_xticks(np.arange(1, len(batches)+1, 9))
ax1.set_ylabel('accuracy')
ax1.grid()
acc_plt = ax1.plot(batches, accuracy, color='red', label='acc')
loss_plt = ax2.plot(batches, loss, color='blue', label='loss')
ax2.set_ylabel('loss')
ax2.set_yticklabels(np.linspace(3, 10, 9))
new_tick_locations = np.arange(1, 11)*10
new_tick_labels = range(1, 11)
ax3.set_xlabel('epochs')
ax3.set_xlim(ax1.get_xlim())
ax3.set_xticks(new_tick_locations)
ax3.set_xticklabels(new_tick_labels)
# Set legends and show the plot
TA贡献1801条经验 获得超16个赞
这会失去您对刻度的控制(您没有说是否需要),但会像您所说的那样排列两个 x 轴:(注释新行)
import numpy as np
import matplotlib.pyplot as plt
batches = np.arange(1,101)
epoch_ends = batches[[(i*10)-1 for i in range(1,11)]]
accuracy = np.apply_along_axis(arr=batches, axis=0, func1d=lambda x : x/len(batches))
loss = np.apply_along_axis(arr=batches, axis=0, func1d=lambda x : 1 - (x/len(batches)))
fig, ax1 = plt.subplots( nrows=1, ncols=1 )
ax2 = ax1.twinx()
ax3 = ax1.twiny()
ax1.set_xlabel('batches')
#ax1.set_xticks(np.arange(1, len(batches)+1, 9))
ax1.set_xlim(0, 100) # Set xlim
ax1.set_ylabel('accuracy')
ax1.grid()
ax2.set_ylabel('loss')
ax2.set_yticklabels(np.linspace(3, 10, 9))
ax3.set_xlabel('epochs')
#ax3.set_xticks(epoch_ends)
#ax3.set_xticklabels(range(1, len(epoch_ends)+1))
ax3.set_xlim(0, 10) # Set xlim
acc_plt = ax1.plot(batches, accuracy, color='red', label='acc')
loss_plt = ax2.plot(batches, loss, color='blue', label='loss')
lns = acc_plt+loss_plt
labs = [l.get_label() for l in lns]
ax1.legend(lns, labs, loc=2)
plt.show()
添加回答
举报