Reputation: 11
I'm fairly new to Python and I've come up with an issue on a plot. Can someone explain why this line graph would connect this way? It seems like I am missing a key step in sorting the variables.
To clarify, if the data was set up in this fashion, how would one get a line graph with the points (1,2) moving diagonal to (2,5), down diagonal to (3,1) and then moving up to (4,2) and (5,4)?
import matplotlib.pyplot as plt
a = [3,1,5,4,2]
b = [1,2,4,2,5]
plt.plot(a, b)
Upvotes: 0
Views: 177
Reputation: 28708
It appears as if line is simply joining your observations in the order presented; starting at (3,1)
then to (1,2)
and so on. This makes sense, maybe it's what someone would want, and should be easy enough to fix - just sort your data such that the X value is increasing.
It's easy to sort your a
value; the catch is sorting your b
value in the same way. To do this I'd zip the two together, sort, then unpack.
import matplotlib.pyplot as plt
b = [t[1] for t in sorted(zip(a, b))]
a = sorted(a)
plt.plot(a, b)
Upvotes: 1