0

There are 2 arrays x - is in ascending order, y - chaotic. How display Y in ascendung order, but save (x,y)

Now graphic looks like that


import numpy as np
import matplotlib.pyplot as plt
x=[]
with open('D:\Programming\Contest\stepperf.txt','r') as a:
    for line in a:
        x.append(line.strip())
x =np.array(x)
y=[]
with open('D:\Programming\Contest\Hall.txt','r') as b:
    for line in b:
        y.append(line.strip())
y  = np.array(y)


fig, ax = plt.subplots(figsize=(8, 6))
plt.grid()     
plt.plot(x,y) 

plt.show()



  • Does this answer your question? [Dictionary Iterating -- for dict vs for dict.items()](https://stackoverflow.com/questions/24746712/dictionary-iterating-for-dict-vs-for-dict-items) – JeffUK Nov 22 '20 at 13:45
  • You really need to convert the values from string to numeric before appending them to the lists. E.g. `x.append(int(line.strip()))` – JohanC Nov 22 '20 at 13:49
  • As far as I understand the question, the y values should be plotted in ascending order, totally ignoring their x value. My understanding might be wrong, but if that was the case you could achieve that by using the sorted lists as can be seen in @itaishz answer and then add the following: ax.set_xticks(np.arange(len(x_sorted))) ax.set_xticklabels(x_sorted) plt.plot(np.arange(len(y_sorted)), y_sorted) – BenB Nov 22 '20 at 14:02

1 Answers1

0

Pandas is a great way to keep arrays as a table, and has an elegant solution for your problem:

import pandas as pd
df = pd.DataFrame({'x': x, 'y': y})

We stored your x and y into a DataFrame, df, with two columns - x and y.
Two options to access the data:

  1. df['x'] and df['y'] are Pandas' series objects.
  2. df['x'].values and df['y'].values are back to numpy arrays.

Sorting it, using sort_values:

df_sorted_by_y = df.sort_values(by='y', ascending=True)

Return to numpy arrays:

x_sorted = df_sorted_by_y['x'].values
y_sorted = df_sorted_by_y['y'].values

Edit: In the last code blocked changed df into df_sorted_by_y

itaishz
  • 701
  • 1
  • 4
  • 10
  • 1
    Note that with the values read as strings from file, they will stay of type string and will get sorted weirdly, e.g. `100` coming before `11`. 3-digit strings will be sorted as expected, but not so when different length numbers are mixed. – JohanC Nov 22 '20 at 13:58
  • @JohanC True, did not notice OP doesn't convert them to int/floats. To add to the answer, this can be fixed through Pandas using `df['x'] = df['x'].astype(float)`. – itaishz Nov 22 '20 at 14:02
  • Yes,saw your comment,fixed it. Thanks) – Александр Писарев Nov 22 '20 at 14:03