如何在Y上按升序显示值,但保存其索引.Matplotlib



有两个数组,x-按升序排列,y-混沌。如何按升序显示Y,但保存(x,Y(

现在图形看起来像


import numpy as np
import matplotlib.pyplot as plt
x=[]
with open('D:ProgrammingConteststepperf.txt','r') as a:
for line in a:
x.append(line.strip())
x =np.array(x)
y=[]
with open('D:ProgrammingContestHall.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()

Pandas是将数组作为表保存的好方法,并且为您的问题提供了一个优雅的解决方案:

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

我们将您的xy存储到一个名为df的DataFrame中,其中包含两列xy
访问数据的两个选项:

  1. df['x']df['y']是熊猫的系列对象
  2. CCD_ 8和CCD_

使用sort_values:对其进行排序

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

返回numpy数组:

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

编辑:在最后一个被阻止的代码中,将df更改为df_sorted_by_y

最新更新