在一张3D图像(Python)中绘制多个折线图

时间:2018-08-02 12:42:25

标签: python plot 3d

我正在尝试绘制多个线xz图,每个图的y值不同。但是,每个y值的数据(对应于奇异的xz平面图)都存储在不同的数据文件中。这些文件包括沿网格的各个(x,y)位置的幅度与频率的关系数据。 我要做的是在每个y值处获取xz图,并将它们放入奇异的3D图像中。最终结果将是在x-恒定值下的幅值与频率关系图位置,且y位置不同。如下图所示:

Desired plot

当前,我的程序将绘制多个图形,如上所示。但是,应该有11个不同的地块,但最后只有一个。我的代码如下(注意:对于x = 0和y = 30,我从中获取数据的文件的格式为LT_X_X0_Y30):

import numpy as np
import glob, os
import codecs
import re
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib import colors as mcolors
import numpy as np
import math
import pylab
import sys
#-------------------------------------------------------------------------                   
os.chdir('C:/Users/elarrick/Desktop/201807161056')
dataFolders = glob.glob('./*.ltda')
LTXFiles = [file for file in os.listdir('C:/Users/elarrick/Desktop/201807161056') if (file.endswith('.ltda') and ('LT_X_' in file))]
LTYFiles = [file for file in os.listdir('C:/Users/elarrick/Desktop/201807161056') if (file.endswith('.ltda') and ('LT_Y_' in file))]

def getCoordinate(name):                          #e.g. name = LT_X_X0_Y0
    shortened = name.strip(".\\LT_")               #Takes the first 5 characters away (.\LT_)
    whichAxis = shortened[0] 
    if whichAxis == "X":
        coordinates = shortened.strip("X_")     #e.g. X0_Y0

        underscore_index = coordinates.find('_')
        x_value = int(coordinates[:underscore_index])

        y_index = coordinates.find('Y')         #y-value for the plot is whatever the y-position is
        if len(coordinates) == y_index+5:       #If Y is at index 3, then if total len is 8, Y is a 4-digit number (including negative)
            y_value = int(coordinates[y_index+1:y_index+5])
        elif len(coordinates) == y_index+4:       #If Y is at index 3, then if total len is 7, Y is a 3-digit number (including negative)
            y_value = int(coordinates[y_index+1:y_index+4])
        elif len(coordinates) == y_index+3:       #If Y is at index 3, then if total len is 6, Y is a 2-digit number
            y_value = int(coordinates[y_index+1:y_index+3])
        elif len(coordinates) == y_index+2:
            y_value = int(coordinates[y_index+1])
        return [x_value,y_value]
#------------ Now we have the value of y at which the plot (freq vs openloopmag) is plotted
x = []
y = []
z1 = []
z2 = []
freq = []
OpenLoopMag = []
OpenLoopPhase = []
y_Values = []
x_value_list = []
#---------------------------------------------------------------------------
#                    Get the x values in order
#---------------------------------------------------------------------------
for item in LTXFiles:        
    name, ext = os.path.splitext(item)
    shortened = str(name.strip(".\\LT_"))       #Takes the first 5 characters away (.\LT_)
    whichAxis = shortened[0]                    #Either X or Y
    if whichAxis == "X":            #First, focus only on X-axis data
        if ext == '.ltda':
            try:
                coordinates = getCoordinate(name)               #Returns [x,y] coordinates
                x_value_list.append(int(coordinates[0]))
            except TypeError:
                print "Name of the problematic file is ", name
                sys.exit()

x_value_list = sorted(list(set(x_value_list)))              #Gets the ordered values of X positions (e.g. -150, -120, -90, etc.)
print "\nx_value_list is ", x_value_list
#---------------------------------------------------------------------------
#                   Loop through files and find the ones
#                       that have each value of x
#---------------------------------------------------------------------------
CorrectXValue = []
for x_val in sorted(x_value_list):                          #for each x value in order
    #print "\nThe x value currently being used is ", x_val
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    for item in LTXFiles:
        if ext == '.ltda':
            coordinates = getCoordinate(name)               #Returns [x,y]
            if coordinates[0] == x_val:                 #Hold a constant x value so only y is varied
                print "coordinates with right x value: ", coordinates
                CorrectXValue.append(item)
        else:
                print "Something went wrong - check ColorMap.py"
                sys.exit()
#---------------------------------------------------------------------------
#                   CorrectXValue now has a list of all the
#                       data files with the right x value.
#                   Now, get the data for each of those.
#---------------------------------------------------------------------------
        for i in range(0,len(CorrectXValue)):
            if item == CorrectXValue[i]:
                print "\nItem used", item
                dataLines = []
                f = codecs.open(item, encoding='utf-8')
                for line in f:
                    if '<p>' in line:
                        dataLines.append(line)          #All lines with <p> are an entry in dataLines
                for item in dataLines:
                    item = re.sub("<p>", "", item)
                    item = re.sub("True</p>", "", item)
                    item = item.replace(",", "")
                    splitItem = item.split()
                    freq.append(float(splitItem[0]))    #obtain the data for said x value
                    OpenLoopMag.append(float(splitItem[1]))
                    OpenLoopPhase.append(float(splitItem[2]))
                    y_Values.append(coordinates[1])

            #   This is where I will make the plots for each x position as a function of y
                for f in freq:
                    f = math.log(f)          #Take the logarithm of the values for frequency
                x = freq
                y = y_Values
                z1 = OpenLoopMag
                z2 = OpenLoopPhase

                plt.hold(True)
                ax.plot(x, y, z1, color='k')

            #________ Clear the values for the next data folder_______#            
                x = []
                y = []
                z1 = []
                z2 = []
                dataLines = []
                freq = []
                OpenLoopMag = []
                OpenLoopPhase = []
                y_Values = []    
#---------------------------------------------------------------------------
#                   Now for each x value, plot all the data
#---------------------------------------------------------------------------
    plt.xlabel("Frequency, (Hz)")
    plt.ylabel("Y Value")
    #plt.zlabel("Magnitude")
    #print coordinates
    #print item
    plt.title("X={0}".format(coordinates[0]))
    ticks = [20,40,70,100,200,400,700,1000,2000]
    plt.xticks(ticks,ticks)
    #plt.hold(True) 
    plt.savefig("../plot_X_{0}.png".format(coordinates[0]))
    #plt.show()
    plt.close()

我已经尝试过各种缩进和位置来放置plt.hold(True)和保存图形,尽管显然我还没有弄清楚要更改的内容。

0 个答案:

没有答案