在一对 y 坐标之间画一条线

Plotting a line between a pair of y coordinates

我正在尝试绘制以下代码,其中 data1、data2、data3 是向量。

data1 = np.array(means1) 
print('data1=',data1)

data2 = np.array(ci_l) 
print('data2',data2)

data3 = np.array(ci_h) 
print('data3',data3)

x = data1
y = np.concatenate([data2[:,None],data3[:,None]], axis=1)

print('x=', x,'y=',y)

plt.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
plt.plot(x, [j for (i,j) in y], 'bo', markersize = 4)
plt.show()

对于您在代码中看到的每个 x 点,我有两个 y 点。当我 运行 代码时,我获得以下输出:

data1= [[22.8]
 [31.6]
 [27.4]
 [30.4]
 [30.6]]
data2 [[21.80474319]
 [30.60474319]
 [26.40474319]
 [29.40474319]
 [29.60474319]]
data3 [[23.79525681]
 [32.59525681]
 [28.39525681]
 [31.39525681]
 [31.59525681]]
x= [[22.8]
 [31.6]
 [27.4]
 [30.4]
 [30.6]] y= [[[21.80474319]
  [23.79525681]]

 [[30.60474319]
  [32.59525681]]

 [[26.40474319]
  [28.39525681]]

 [[29.40474319]
  [31.39525681]]

 [[29.60474319]
  [31.59525681]]]

和这个数字:

我的问题是如何绘制连接每个 y 对的线?我的问题与此类似:

<>

我尝试按照建议在代码中添加以下行:

plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black')

但我收到以下错误:

Traceback (most recent call last):
  File "/Users/oltiana/Desktop/datamining/chapter4.py", line 151, in <module>
    plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black')
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/matplotlib/pyplot.py", line 3019, in plot
    return gca().plot(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/matplotlib/axes/_axes.py", line 1605, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 315, in __call__
    yield from self._plot_args(this, kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
    raise ValueError(f"x and y can be no greater than 2D, but have "
ValueError: x and y can be no greater than 2D, but have shapes (2, 5, 1) and (2, 5, 1)

我尝试使用 shape 和 reshape 解决问题,但仍然无效。任何建议都会对我有所帮助。谢谢!

尝试写作

for x1,y1y2 in zip(x,y):
    
    plt.plot([x1,x1],y1y2,'k-') #'k-' to prevent automatic coloring

之前

plt.plot(x, [i for (i,j) in y], 'ro', markersize = 4)
plt.plot(x, [j for (i,j) in y], 'bs', markersize = 4)

这将为每对点绘制一个两点图。 这将在视觉上起作用,但可能会弄乱自动图例

我注意到您的数据数组看起来都像二维列表 - 每个数字都是其自身列表中的唯一元素! ([[22.8], [31.6], ...] 而不是 [22.8, 31.6, ...]

这就是您出现形状错误的原因。有几种方法可以解决此问题,但一种简单的方法是在每个数组上调用 .flatten()。这将它减少为一维的,您的代码可以很好地处理这样的数据。

data1 = np.array(means1).flatten()
data2 = np.array(ci_l).flatten()
data3 = np.array(ci_h).flatten()

...