Reputation: 345
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.
Upvotes: 1
Views: 2656
Reputation: 114230
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
Upvotes: 2