【问题标题】:I can make my scatterplot, but I can not draw my line with matplotlib in the same figure我可以制作我的散点图,但我不能在同一张图中用 matplotlib 画线
【发布时间】:2021-03-12 12:41:35
【问题描述】:

我是初学者,所以这可能是一个愚蠢的问题。如果我运行以下代码,我会看到 xy 的散点图,但回归线 plt.plot(x, estimated_y, color="r", linewidth=3.0) 没有出现。我使用协方差矩阵估计了yxyestimated_y 都是 numpy 数组。如果我单独运行plt.plot(x, estimated_y, color="r", linewidth=3.0),我会看到一个空图。

plt.figure()
plt.scatter(x,y)
plt.plot(x, estimated_y, color="r", linewidth=3.0) 
plt.show()
plt.xlabel("x")
plt.ylabel("y")

感谢大家的帮助!

【问题讨论】:

  • 如果不显示整个代码和数据集,很难说你做了什么。首先:您确定estimated_y 包含数据并且在图的限制范围内吗?

标签: python matplotlib plot regression scatter-plot


【解决方案1】:

您的代码看起来相当不错。我添加了一些随机数据来创建一个最小的可重现示例:

import matplotlib.pyplot as plt

# create dummy data
x = list(range(0,10))
y = list(range(10,0,-1))
estimated_y = [1]*10

plt.figure()
plt.scatter(x,y)
plt.plot(x, estimated_y, color="r", linewidth=3.0) 
plt.show()
# do not add anything to the axes after this command. The command forces to terminate the "rendering", which is why everything afterwards opens a new plot

输出看起来不错:

但是,您可以确保绘制到相同的轴(一个图形可能包含多个轴或“子图”)

# open a figure + create a single axis
fig, ax = plt.subplots()
ax.scatter(x,y)
ax.plot(x, estimated_y, color="r", linewidth=3.0) 
plt.show()

您从基础调用的任何绘图函数,例如matplotlib.pyplot.plot()plt.plot() 因为您已将库的一部分重命名/导入为 plt,将绘制到当前活动的轴。这应该适用于您的情况。

好处是,使用轴时,您可以计算在轴上绘制的线数: len(ax.get_lines())

1

它是一个,因为scatter() 不会绘制“线”而是“点”......现在,如果你用你的数据调用它,它也应该返回1。如果是这样并且您看不到红线,则可能是您的数据包含NaNs 或者它的绘制超出了限制。如果返回0,则您已将其绘制到一些不同的(可能是不可见的或尚未绘制的)轴上。

【讨论】:

  • 感谢您的评论。它仍然没有奇怪的工作。实际上,我尝试将您的变体与子图一起使用,现在它告诉我,如果我要求 len(ax.get_lines()),则会绘制 20 条线。可能是因为:我的 numpy 数组estimated_y 包含 20 个数字。
  • 嗯,我对此表示怀疑。不过,您可以通过调用 ax.plot(x, estimated_y.tolist()) 来检查这个假设
猜你喜欢
  • 2012-08-21
  • 2012-05-14
  • 2016-07-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 2021-07-21
  • 2016-02-20
  • 2021-05-12
相关资源
最近更新 更多