x,y gridin的颜色图-Python

时间:2018-08-07 18:31:17

标签: python matplotlib colormap

我正在使用从共振频率获取的数据来创建彩色图,作为x和y位置的函数。在浏览资源时(显示了随机的彩色图) here,使用meshgrid的彩色地图(如here等),我遇到了一个问题,我需要数据为网格格式,但我所需要的全部数据是我的 x值,y值和相应的共振频率。

我不擅长曲面创建,如果我没有连续的Z值来为x和x的每个值创建曲面,meshgrid对我来说就没有意义了y。

下面是2个完整的代码版本,每个版本都执行我不想要的事情。

版本1 :绘制随机形状和颜色的正方形(由于我将color设置为等于{{1} }。我只是不知道该用什么替换。)

np.random.uniform(...)

版本2 :没有要绘制的连续Z“表面”-我只有离散的值,我需要在每个值上显示颜色(x, y)位置。

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
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import math
import pylab
import sys
#-------------------------------------------------------------------------
directoryUsed = 'C:/Users/elarrick/Desktop/201807161056'

os.chdir(directoryUsed)
dataFolders = glob.glob('./*.ltda')

LTXFiles = [file for file in os.listdir(directoryUsed) if (file.endswith('.ltda') and ("LT_X" in file))]
#-------------------------------------------------------------------------
#               Function for getting coordinates in [x,y] form
#-------------------------------------------------------------------------
def getCoordinate(name):                          #e.g. name = LT_X_X0_Y0
    name = name.strip(".\\")
    shortened = name.strip("LT_")               #Takes the first 3 characters away
    whichAxis = shortened[0] 
    if whichAxis == "X":
        coordinates = shortened.strip("X_")     #e.g. X0_Y0
        coordinates = coordinates.strip(".ltda")

        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]
#-------------------------------------------------------------------------
#               Function for making color map
#-------------------------------------------------------------------------
def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)
#-------------------------------------------------------------------------
#                           Get the data
#-------------------------------------------------------------------------
y_value_list = []
x_value_list = []

for item in LTXFiles:
    name, ext = os.path.splitext(item)
    if ext == '.ltda':
        try:
            coordinates = getCoordinate(name)               #Returns [x,y] coordinates
            x_value_list.append(int(coordinates[0]))
            y_value_list.append(int(coordinates[1]))
        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.)
y_value_list = sorted(list(set(y_value_list)))              #Gets the ordered values of Y positions (e.g. -150, -120, -90, etc.)
#-------------------------------------------------------------------------
#           We now have the values of x and y in order.
#           Get the peak of the Mag vs. Freq curves
#-------------------------------------------------------------------------
x = []
y = []
dataLines = []
freq = []
OpenLoopMag = []
OpenLoopMagResFreq = []
OpenLoopPhase = []
OpenLoopPhaseResFreq = []
FirstMaximumOpenLoopMag = []
FirstMinimumOpenLoopMag = []
FirstMaximumOpenLoopPhase = []
FirstMinimumOpenLoopPhase = []
n_bins = 0
for x_val in x_value_list:              #for each x value in order
    for y_val in y_value_list:
        n_bins += 1
        print "\nThe x value currently being used is ", x_val
        print "\nThe y value currently being used is ", y_val
        for dataFile in LTXFiles:
            coordinate = getCoordinate(dataFile)                    #has form [x,y]
            if coordinate[0] == x_val and coordinate[1] == y_val:           #If coordinates match
                f = codecs.open(dataFile, 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,y] values
                    OpenLoopMag.append(float(splitItem[1]))
                    OpenLoopPhase.append(float(splitItem[2]))

#--------------------------------------------------------------------------------------------
#           We now have Freq, OpenLoopMag, and OpenLoopPhase
#                   for each value of x,y.
#--------------------------------------------------------------------------------------------

                x.append(x_val)
                y.append(y_val)

                maxOpenLoopMag = max(OpenLoopMag)
                maxOpenLoopPhase = max(OpenLoopPhase)
                for i in range(0,len(OpenLoopMag)):
                    if OpenLoopMag[i] == maxOpenLoopMag:
                        OpenLoopMagResFreq.append(freq[i])
                        break
                for i in range(0,len(OpenLoopPhase)):
                    if OpenLoopPhase[i] == maxOpenLoopPhase:
                        OpenLoopPhaseResFreq.append(freq[i])
                        break
minimumMagResFreq = min(OpenLoopMagResFreq)
maximumMagResFreq = max(OpenLoopMagResFreq)

c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = len(x)
print "x = ", x
print "y = ", y
colors = np.random.uniform(minimumMagResFreq, maximumMagResFreq, size=(N,))
plt.scatter(x,y,OpenLoopMagResFreq, c=colors, cmap=rvb, marker = "s")
plt.xlabel('X position')
plt.ylabel('Y position')
plt.title('Resonant Frequency Visualization')
plt.colorbar()
plt.show()

版本1每次运行代码时都会给我这张图片不同的颜色enter image description here

第2版给我这个错误:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import glob, os
import codecs
import re
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib import colors as mcolors
import math
import pylab
import sys
#--------------------------------------------------------------------------------------------
directoryUsed = 'C:/Users/elarrick/Desktop/201807161056'

os.chdir(directoryUsed)
dataFolders = glob.glob('./*.ltda')
LTXFiles = [file for file in os.listdir(directoryUsed) if (file.endswith('.ltda') and ("LT_X" in file))]

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

        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]
#--------------------------------------------------------------------------------------------
#                           Get the data
#--------------------------------------------------------------------------------------------
y_value_list = []
x_value_list = []

for item in LTXFiles:
    name, ext = os.path.splitext(item)
    if ext == '.ltda':
        try:
            coordinates = getCoordinate(name)               #Returns [x,y] coordinates
            x_value_list.append(int(coordinates[0]))
            y_value_list.append(int(coordinates[1]))
        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.)
y_value_list = sorted(list(set(y_value_list)))              #Gets the ordered values of Y positions (e.g. -150, -120, -90, etc.)
#--------------------------------------------------------------------------------------------
#           We now have the values of x and y in order.
#           Get the peak of the Mag vs. Freq curves
#--------------------------------------------------------------------------------------------
x = []
y = []
dataLines = []
freq = []
OpenLoopMag = []
OpenLoopMagResFreq = []
OpenLoopPhase = []
OpenLoopPhaseResFreq = []
FirstMaximumOpenLoopMag = []
FirstMinimumOpenLoopMag = []
FirstMaximumOpenLoopPhase = []
FirstMinimumOpenLoopPhase = []
n_bins = 0
for x_val in x_value_list:              #for each x value in order
    for y_val in y_value_list:
        n_bins += 1
        print "\nThe x value currently being used is ", x_val
        print "\nThe y value currently being used is ", y_val
        for dataFile in LTXFiles:
            coordinate = getCoordinate(dataFile)                    #has form [x,y]
            if coordinate[0] == x_val and coordinate[1] == y_val:           #If coordinates match
                f = codecs.open(dataFile, 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,y] values
                    OpenLoopMag.append(float(splitItem[1]))
                    OpenLoopPhase.append(float(splitItem[2]))

#--------------------------------------------------------------------------------------------
#           We now have Freq, OpenLoopMag, and OpenLoopPhase
#                   for each value of x,y.
#--------------------------------------------------------------------------------------------

                x.append(x_val)
                y.append(y_val)

                maxOpenLoopMag = max(OpenLoopMag)
                maxOpenLoopPhase = max(OpenLoopPhase)
                for i in range(0,len(OpenLoopMag)):
                    if OpenLoopMag[i] == maxOpenLoopMag:
                        OpenLoopMagResFreq.append(freq[i])
                        break
                for i in range(0,len(OpenLoopPhase)):
                    if OpenLoopPhase[i] == maxOpenLoopPhase:
                        OpenLoopPhaseResFreq.append(freq[i])
                        break

X, Y = np.meshgrid(x, y)
#Z = np.cos(X) * np.sin(Y) * 10
a = np.zeros(len(x))+x
b = np.zeros(len(y))+y
Z = np.meshgrid(a,b)

colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]  # R -> G -> B
n_bins = [n_bins, n_bins, n_bins, n_bins]  # Discretizes the interpolation into bins
cmap_name = 'my_list'
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
for n_bin, ax in zip(n_bins, axs.ravel()):
    # Create the colormap
    cm = LinearSegmentedColormap.from_list(
        cmap_name, colors, N=n_bin)
    # Fewer bins will result in "coarser" colomap interpolation
    im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm)
    ax.set_title("N bins: %s" % n_bin)
    fig.colorbar(im, ax=ax)
plt.show()

0 个答案:

没有答案