首页 > 解决方案 > matplotlib 图形输出一团糟

问题描述

一直在尝试制作情节,但输出一团糟,代码似乎没有问题。谁能帮忙解释一下?

数字

x = np.random.rand(10)
y = np.sin(x)
fig, ax = plt.subplots(111)
ax[0].plot(x, y)
plt.show()
fig.savefig("1.png")

标签: matplotlib

解决方案


你正在路过plt.subplots(111)。您正在传递 111 行:matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw) 如果您只想要一个图表,您可以使用:

import matplotlib.pyplot as plt
import random
import numpy as np
x = np.random.rand(10)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

输出:

输出图

你的意思是使用matplotlib.pyplot.subplot(*args, **kwargs)

import matplotlib.pyplot as plt
import random
import numpy as np
x = np.random.rand(10)
y = np.sin(x)
plt.subplot(111)
ax = plt.subplot(1,1,1)
ax.plot(x,y)
plt.show()

输出:

输出

另一个使用示例plt.subplot(311)

x = np.random.rand(10)
y = np.sin(x)
plt.subplot(311)
ax1 = plt.subplot(1,1,1)
ax1.plot(x,y,c='red')
plt.show()
ax2 = plt.subplot(2,1,1)
ax2.plot(x,y,c='green')
plt.show()
ax2 = plt.subplot(3,1,1)
ax2.plot(x,y,c='blue')
plt.show()

输出:

(311) 情节


推荐阅读