我有 4 个数字 (y1,y2,y3,y4),我想在公共(public) x 轴 (yr1,yr2,yr3,m1,m2,m3,m4,m5) 上绘制。然而,在这段代码中,我将 axaxis 保持为单独的,因为我试图首先掌握正确的基础知识。
import matplotlib.pyplot as plt
import numpy as np
plt.figure(1)
xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm5']
y1 = np.array([.73,.74,.71,.75,.72,.75,.74,.74])
y2 = np.array([.82,.80,.77,.81,.72,.81,.77,.77])
y3 = np.array([.35,.36,.45,.43,.44,.45,.48,.45])
y4 = np.array([.49,.52,.59,.58,.61,.65,.61,.58])
plt.subplot(221)
plt.plot(xaxis,y1)
plt.subplot(222)
plt.plot(xaxis,y2)
plt.subplot(223)
plt.subplot(xaxis,y3)
plt.subplot(224)
plt.subplot(xaxis,y4)
plt.show()
收到此错误
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-23-dfe04cc8c6c4> in <module>
14 plt.plot(xaxis,y2)
15 plt.subplot(223)
---> 16 plt.subplot(xaxis,y3)
17 plt.subplot(224)
18 plt.subplot(xaxis,y4)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in subplot(*args, **kwargs)
1074
1075 fig = gcf()
-> 1076 a = fig.add_subplot(*args, **kwargs)
1077 bbox = a.bbox
1078 byebye = []
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\figure.py in add_subplot(self, *args, **kwargs)
1412 self._axstack.remove(ax)
1413
-> 1414 a = subplot_class_factory(projection_class)(self, *args, **kwargs)
1415
1416 return self._add_axes_internal(key, a)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_subplots.py in __init__(self, fig, *args, **kwargs)
62 # num - 1 for converting from MATLAB to python indexing
63 else:
---> 64 raise ValueError(f'Illegal argument(s) to subplot: {args}')
65
66 self.update_params()
ValueError: Illegal argument(s) to subplot: (['y1', 'y2', 'y3', 'm1', 'm2', 'm3', 'm4', 'm5'], array([0.35, 0.36, 0.45, 0.43, 0.44, 0.45, 0.48, 0.45]))
请帮助理解这里的问题!
最佳答案
重用 Sahith Kurapati 的代码只是为了提供更简洁的解决方案。这样,您可以共享坐标轴,并且如果线条和图表样式都应该具有相同的样式,则仅配置一次。
import matplotlib.pyplot as plt
import numpy as np
plt.figure(1)
xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm5']
yy = np.array([[.73,.74,.71,.75,.72,.75,.74,.74],
[.82,.80,.77,.81,.72,.81,.77,.77],
[.35,.36,.45,.43,.44,.45,.48,.45],
[.49,.52,.59,.58,.61,.65,.61,.58]])
fig, axes = plt.subplots(2, 2)
for y, ax in zip(yy, axes.ravel()):
ax.plot(y)
plt.show()
关于python - Matplotlib - 值错误 : Illegal argument(s) to subplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618261/