1

I have an ascii file i with two variables and I want to create a scatterplot and add the line y=x in the scatterplot. The code for creating the scatterplot is below.

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

val1 = np.loadtxt(i, usecols=0)
val2 = np.loadtxt(i, usecols=1)
fig, ax = plt.subplots(1, 1)
fig.set_size_inches(6, 6)
plt.scatter(val1, val2)
plt.savefig(outfile, bbox_inches='tight', format='png', dpi=200)

How to define the plot of line y = x without define the axis scale? Because the scale of the axes is dynamic based on the data. I want to do that for multiple files.

2
  • 2
    plt.plot(val1, val1) might work Commented Jan 12, 2022 at 20:03
  • @MSH. No it won't Commented Jan 12, 2022 at 20:10

1 Answer 1

2

While there are such things as axvline and axhline, and their less popular, but more general, sibling plt.axline. You can specify a pair of points, or a starting point and a slope to draw an infninite line:

plt.axline([0, 0], slope=1)

Another approach is to draw a line in the region of your data:

xmin = val1.min()
xmax = val1.max()
ymin = val2.min()
ymax = val2.max()
xmargin = 0.1 * (xmax - xmin)
ymargin = 0.1 * (ymax - ymax)
margin = 0.5 * (xmargin + ymargin)
cmin = max(ymin, xmin)
cmax = min(xmax, ymax)
plt.plot(*[[cmin - margin, cmax + margin]] * 2)

Both methods are shown below with plt.axis('equal') and the following dataset:

val1, val2 = np.random.uniform([10, 20], size=(100, 2)).T

enter image description here

Sign up to request clarification or add additional context in comments.

10 Comments

What about the (rather new) function ax.axline() which accepts a slope (or two points) as parameter?
Thank you. However I wanted to plot the line y=x. I tried the code but I didn't;t get the line.
@JohanC I tried also the ax.axline but the problem is that I do not know the scale of each dataset since I use it for different files
@Nat. This plots the line y=x. When you plot anything of the form plt.plot([p1, p2], [p1, p2]), that's clearly along the line y=x
@Nat. Are you looking for plt.axis('equal')? I can add that to the answer...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.