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?
Thank you in advance!
An alternative to sort the lists would be to use NumPy arrays and use
np.sort()
for sorting. The advantage with using arrays would be a vectorized operation while computing a function like y=f(x). Following is an example of plotting a normal distribution:Without using sorted data
Output 1
With using np.sort() This allows straightforwardly using sorted array
x
while computing the normal distribution.Alternatively if you already have both x and y data unsorted, you may use
numpy.argsort
to sort them a posterioriIn both cases the output is
Output 2
Sort by the value of x-axis before plotting. Here is an MWE.
For small data,
zip
(as mentioned by other answerers) is enough.The result,
just do this
sorted function will sort according to the 1st argument i.e x values
I think you need to sort one array and the other array should also get sorted based on the first array. I got this solution from some other stack overflow question. Most probably this should be your solution.
Now plot those two values, you get a correct graph.
You can convert your arrays to numpy arrays, then use argsort on the first array, take the the array and sort both arrays with the argsort array.
It is easier to
zip
, sort and unzip
the two lists of data.Example:
See the zip documentation here: https://docs.python.org/3.5/library/functions.html#zip