Issue
Basically I have two arrays, one containing the values of the x-axis and the second containing the values of the y-axis. The problem is, when I do
plt.semilogy(out_samp,error_mc)
I get this
Which doesn't make any sense. That is because the plot functions plots everything as it encounters in the x array, not caring whether it's sorted in ascending order or not. How can I sort these two arrays so that the x array is sorted by increasing value and the y axis sorted in the same way so that the points are the same but the plot is connected so that it doesn't make this mess?
Solution
Sort by the value of x-axis before plotting. Here is an MWE.
import itertools
x = [3, 5, 6, 1, 2]
y = [6, 7, 8, 9, 10]
lists = sorted(itertools.izip(*[x, y]))
new_x, new_y = list(itertools.izip(*lists))
# import operator
# new_x = map(operator.itemgetter(0), lists) # [1, 2, 3, 5, 6]
# new_y = map(operator.itemgetter(1), lists) # [9, 10, 6, 7, 8]
# Plot
import matplotlib.pylab as plt
plt.plot(new_x, new_y)
plt.show()
For small data, zip
(as mentioned by other answerers) is enough.
new_x, new_y = zip(*sorted(zip(x, y)))
The result,
Answered By - SparkAndShine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.