我有一个从DataFrame构建的散点图 – 它显示了两个变量的相关性 – 长度和年龄
import matplotlib.pyplot as plt
df = DataFrame (......)
plt.title ('Fish Length vs Age')
plt.xlabel('Length')
plt.ylabel('Age (days)')
plt.scatter(df['length'],df['age'])
现在我想在这个散点图中添加一条给定斜率为0.88的线.我该怎么做呢?
附:所有的例子我都设法找到了使用点而不是斜率来绘制线
UPDATE.我重读了这个理论 – 事实证明,应该根据数据点绘制相关系数的事实由我组成:)部分原因是我头脑中的这个图像
但是我仍然对matplotlib的线条绘图功能感到困惑
解决方法:
在@ JinxunLi的答案基础上,您只想添加一条连接两点的线.
这两个点有x和y坐标,因此对于这两个点,你将有四个数字:x_0,y_0,x_1,y_1.
假设您希望这两个点的x坐标跨越x轴,那么您将手动设置x_0和x_1:
x_0 = 0
x_1 = 5000
或者,您可以从轴获取最小值和最大值:
x_min, x_max = ax.get_xlim()
x_0 = x_min
x_1 = x_max
slope = (y_1 - y_0) / (x_1 - x_0)
这可以重新排列为:
(y_1 - y_0) = slope * (x_1 - x_0)
这个斜率有无数个平行线,因此我们必须设置其中一个点开始.对于这个例子,让我们假设你想让线穿过原点(0,0)
x_0 = 0 # We already kNow this as it was set earlier
y_0 = 0
现在,您可以将y_1的公式重新排列为:
y_1 = slope * (x_1 - x_0) + y_0
如果您知道您希望斜率为0.88,那么您可以计算另一个点的y位置:
y_1 = 0.88 * (5000 - 0) + 0
对于您在问题中提供的数据,具有斜率0.88的线将非常快地从y轴的顶部飞出(在上面的示例中y_1 = 4400).
在下面的例子中,我放入了一条斜率= 0.03的线.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# simulate some artificial data
# =====================================
df = pd.DataFrame( { 'Age' : np.random.rand(25) * 160 } )
df['Length'] = df['Age'] * 0.88 + np.random.rand(25) * 5000
# plot those data points
# ==============================
fig, ax = plt.subplots()
ax.scatter(df['Length'], df['Age'])
# Now add on a line with a fixed slope of 0.03
slope = 0.03
# A line with a fixed slope can intercept the axis
# anywhere so we're going to have it go through 0,0
x_0 = 0
y_0 = 0
# And we'll have the line stop at x = 5000
x_1 = 5000
y_1 = slope (x_1 - x_0) + y_0
# Draw these two points with big triangles to make it clear
# where they lie
ax.scatter([x_0, x_1], [y_0, y_1], marker='^', s=150, c='r')
# And Now connect them
ax.plot([x_0, x_1], [y_0, y_1], c='r')
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。