python中绘图上的y轴不按值排序

时间:2021-02-01 19:05:06

标签: python matplotlib

我很难让 y 轴标签按它们在 python 中的值在图上排序。 this Firebase engineer 我在另一个板上读到他们的问题是需要尝试将字符串转换为浮点数 (see plot),但是在我的代码上尝试这样做时,它并没有解决问题。我从 .dat 文件中提取数据并从这些文件中提取温度以用作 y 标签,将其固定到数据上,然后绘制它。我希望 y 轴按照这些标签的值进行组织。不确定我是不是在正确的位置转换或其他一些问题。代码如下。非常感谢帮助让我的数据按 y 轴标签值排序!!

#Temperature depenedent data organization
import glob
import numpy as np
import matplotlib.pyplot as plt

spacer=0 #keeps track of y shift in plots, is zero for first line after +=
labels=[]
label_position=[]

for filename in glob.glob('*_610_1010_*.dat'):   #defines what files it is going to perform loops on
   
    linenumber=0
    spacer+=40    #normalizer thing, change this number to increase/decrease y spacing
   
    num_lines=sum(1 for line in open(filename))-7    #says how many lines in text file
    data=np.zeros((num_lines,2))  #matrix size of data
    
    for line in open(filename, 'r'):    # loop within each data file to go through and sort lines
       
        linenumber+=1       #adds one to variable each time loop runs to count line numbers
       
        if linenumber==3:
            actual_T=float(line[22:28]) #pulls out actual temperature value from .dat file line 3
            labels.append(float(actual_T) )     #using actual_T value for the legend entry of data set
       
        if linenumber==4:
            set_T=line[18:25]  #pulls out set temperature value from .dat file line 4   
        
        if linenumber>7:     #remaining contents of dat file that is just the data

            array=(line.split("\t"))    #data array for that line, splitting columns by deliminator
            if linenumber==8:
                    normalize=np.float(array[1])       #normalizing y in phase and converting to float
                    container=np.float(array[1])/normalize+spacer  #putting y data in container and taking noramlized values and adding spacer to create y-offset
                    label_position.append(container)       #positioning y-axis label with the offset
            data[linenumber-8,0]=array[0]  #saves frequency values to data, x values
            data[linenumber-8,1]=np.float(array[1])/normalize+spacer #saves in phase y values to data

    fig=plt.figure(1)
  
    plt.plot(data[:,0], data[:,1], label=actual_T)     #creates plot of all data sets from arrays in the loop
    plt.xlim(850,1010)     #frequency, x, range of plot
    plt.xlabel('Frequency (Hz)', fontsize=20)
    plt.ylabel('Temperatue (K)', fontsize=20)

    
    fig_size = plt.rcParams["figure.figsize"] 
    fig_size[0] = 10  # Set figure width to 10 and height to 8
    fig_size[1] = 28
    

    plt.rcParams["figure.figsize"] = fig_size
    

plt.yticks(label_position,labels)   #adding y ticks as the actual_T tied to each data set
fig.savefig('fig1.jpeg')   #saves combines graph to current folder in jpeg 
plt.show()

1 个答案:

答案 0 :(得分:0)

在绘图前按 y 轴的值排序。这是一个例子。

import itertools
import matplotlib.pylab as plt

x = [6, 7, 8, 9, 10]
y = [3, 5, 6, 1, 2]

x1 = [6, 7, 8, 9, 15]
y1 = [13, 15, 16, 11, 20]

lists = sorted(zip(*[x, y]))
new_x, new_y = list(zip(*lists))

lists1 = sorted(zip(*[x1, y1]))
new_x1, new_y1 = list(zip(*lists1))

# 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
plt.plot(new_x, new_y, 'b' , marker="o", lw=2.9)
plt.plot(new_x1, new_y1, 'r' , marker="*", lw=2.9)
plt.grid()

enter image description here

P.S. :当您从 *.dat 文件中导入相同的数据时,我不确定您的数据会是什么样子,我认为这是感测数据。我使用随机数据。但逻辑保持不变。

对于小数据,zip 就足够了。

new_x, new_y = zip(*sorted(zip(x, y)))