首页 > 解决方案 > 无法在 matplotlib 图中设置 xlabel 和 ylabel

问题描述

我是 matplotlib 的新手,无法为我的绘图设置轴标签。我也试过 plt.xlabel("xlabel") 和 ax1.set(xlabel="Images") 但都失败了。有任何想法吗?

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
fig.suptitle("Cross Entropy Loss", fontsize=20)

ax1.set_xlabel('xlabel')
ax1.set_ylabel('ylabel')

def animate(i):
    pullData = open("loss1.txt", "r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    for eachLine in dataArray:
        if len(eachLine) > 1:
            x, y = eachLine.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax1.clear()
    ax1.plot(xar, yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.title("Cross Entropy Loss")
plt.show()

标签: pythonmatplotlibplot

解决方案


您在执行“ax1.clear()”时正在清除轴,因此“ax1.set_xlabel('xlabel')”和“ax1.set_ylabel('ylabel')”没有显示您想要的内容。

要解决这个问题,只需在清除 ax1同时放置“set_x_label”和“set_y_label” 。代码应类似于以下内容:

...
    for eachLine in dataArray:
        if len(eachLine) > 1:
            x, y = eachLine.split(',')
            xar.append(int(x))
            yar.append(int(y))
    ax1.clear()
    ax1.set_xlabel('xlabel')
    ax1.set_ylabel('ylabel')
    ax1.plot(xar, yar)
...

推荐阅读