使用python的matplotlib向散点图添加线 [英] Adding line to scatter plot using python's matplotlib
本文介绍了使用python的matplotlib向散点图添加线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用python的
这样做使我得到了结果:
#散点图x = data_calc_hourly.tempy = data_obs_hourly.templineStart = 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()
有没有更好的方法?
解决方案
这将绘制一条与散点图数据无关的对角线,即使您调整窗口大小,该对角线也保持以轴为根:
将 numpy 导入为 np导入matplotlib.pyplot作为plt将 matplotlib.lines 作为 mlines 导入导入 matplotlib.transforms 作为 mtransformsx,y = np.random.random((2,100))* 2无花果,ax = plt.subplots()ax.scatter(x,y,c ='黑色')line = mlines.Line2D([0, 1], [0, 1], color='红色')变换 = ax.transAxesline.set_transform(transform)ax.add_line(line)plt.show()
I am using python's matplotlib and 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.
This should be the final plot:
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 ?
解决方案
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()
这篇关于使用python的matplotlib向散点图添加线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文