使用python的matplotlib向散点图添加线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40516661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:37:11  来源:igfitidea点击:

Adding line to scatter plot using python's matplotlib

pythonmatplotlib

提问by Manuel

I am using python's matplotliband want to create a matplotlib.scatter()with additional line. The line should proceed from the lower left corner to the upper right corner independent of the scatters content. A linear regression through the data, like in this post, is not what I am looking for. Also it should be dynamically and independent of the scatter input.

我正在使用 python 的matplotlib并想创建一个matplotlib.scatter()附加行。这条线应该从左下角到右上角,与分散的内容无关。数据的线性回归,就像在这篇文章中一样,不是我想要的。它也应该是动态的并且独立于分散输入。

This should be the final plot:

这应该是最后的情节:

enter image description here

在此处输入图片说明

EDIT:

编辑:

Doing this got me the result:

这样做让我得到了结果:

# Scatter Plot
x = data_calc_hourly.temp
y =  data_obs_hourly.temp

lineStart = data_calc_hourly.temp.min() 
lineEnd = data_calc_hourly.temp.max()  

plt.figure()
plt.scatter(x, y, color = 'k', alpha=0.5)
plt.plot([lineStart, lineEnd], [lineStart, lineEnd], 'k-', color = 'r')
plt.xlim(lineStart, lineEnd)
plt.ylim(lineStart, lineEnd)
plt.show()

Is there any better way ?

有没有更好的方法?

回答by unutbu

This draws a diagonal line which is independent of the scatter plot data and which stays rooted to the axes even if you resize the window:

这将绘制一条与散点图数据无关的对角线,即使您调整窗口大小,该对角线仍以轴为根:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms

x, y = np.random.random((2, 100))*2
fig, ax = plt.subplots()
ax.scatter(x, y, c='black')
line = mlines.Line2D([0, 1], [0, 1], color='red')
transform = ax.transAxes
line.set_transform(transform)
ax.add_line(line)
plt.show()

enter image description here

在此处输入图片说明

回答by Jo?o Almeida

Besides unutbu's answer one other option is to get the limits of the axis after you ploted the data and to use them to add the line. After this you will still need to change back the axis limits as they would change with the addition of the line:

除了 unutbu 的回答之外,另一种选择是在绘制数据后获取轴的限制并使用它们添加线。在此之后,您仍然需要更改轴限制,因为它们会随着行的添加而改变:

# Scatter Plot
x = data_calc_hourly.temp
y =  data_obs_hourly.temp

lineStart = data_calc_hourly.temp.min() 
lineEnd = data_calc_hourly.temp.max()  

plt.figure()
plt.scatter(x, y, color = 'k', alpha=0.5)
y_lim = plt.ylim()
x_lim = plt.xlim()
plt.plot(x_lim, y_lim, 'k-', color = 'r')
plt.ylim(y_lim)
plt.xlim(x_lim)
plt.show()