'Adding line to scatter plot using python's matplotlib

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:

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 ?



Solution 1:[1]

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:

# 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()

Solution 2:[2]

I have tried updating the min and max limits for the cases where X and Y axis have different max and min data.

x = data_calc_hourly.temp
y =  data_obs_hourly.temp

calc_min = data_calc_hourly.temp.min()
calc_max = data_calc_hourly.temp.max()

obs_min = data_obs_hourly.temp.min()
obs_max = data_obs_hourly.temp.max()

lineStart = min(calc_min,obs_min)
lineEnd = max(calc_max,obs_max)

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 João Almeida
Solution 2 Johnny