繁体   English   中英

带有数字到 rgba 的 Python .txt 文件

[英]Python .txt file with numbers to rgba

有人可以帮助我完成我的项目吗? 我想通过数据记录器将来自几个温度传感器的数据保存到一个文件中,然后用 Python 程序对其进行分析。 那是我的问题。 处理完数据后,然后创建一个交互式 3D 地图,该地图使用传感器的测量结果作为颜色等级。

我提前很抱歉,以防我错过了什么,或者没有提供足够的信息。 这是我在这里问的第一个问题。 我以前没有使用过 Python,所以我仍然是一个“菜鸟”。

附上我有当前的代码。 我希望很明显我想要什么,但是当我想将 .txt 文件中的数据用于 RGB / RGBA 时出现的错误是:

10., 20., 30., 40., 50., 60., 50., 60., 50., 40., 30., 20., 10. -> RGBA 参数无效:nan 或者,如果我有它转换为数组无效的 RGBA 参数:0.0

我发现RGB值只能在0.0和1.0之间处理,但是我的“颜色”数组还可以(见代码)

我没有看到错误。 我希望有人能帮帮忙。 提前致谢。

/ 最小:(错误可能在哪里)

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np 

fig = plt.figure(figsize=plt.figaspect(1))
ax = fig.add_subplot(1, 1, 1, projection='3d')

data_file = np.genfromtxt('data_file.txt', delimiter=',')
color = mpl.colors.to_rgba_array(data_file[:,0], alpha=None)

c = np.abs(color)
cmhot = plt.get_cmap("hot")
ax.scatter(X, Y, Z, color, s=50, c=c, cmap=cmhot)

/ 完整代码:

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np
import pandas as pd
from pandas import DataFrame 


# set up a figure
fig = plt.figure(figsize=plt.figaspect(1))

ax = fig.add_subplot(1, 1, 1, projection='3d')

########################the part not working#########################

# load the data file
data_file = np.genfromtxt('data_file.txt', delimiter=',')

#possible processing / not working
#data_file = np.array(data_file)
#data_file = (data_file-min(data_file))/(max(data_file)-min(data_file))

# parse good sensor data from imported data
color = mpl.colors.to_rgba_array(data_file[:,0], alpha=None)

########################the part not working#########################

arrA = ([[ -4. ],
         [ 0. ],
         #...etc.
         [ 0. ],
         [ 4. ]])

arrB = ([[ -4. ],
         [ -4. ],
         #...etc.
         [ 4. ],
         [ 4. ]])

arrC = ([[ -30. ],
         [ -30. ],
         #...etc.
         [ -30. ],
         [ -30. ]])

#color = ([ 0. , 10. , 20. , 30. , 40. , 50. , 60. , 50. , 40. , 30. , 20. , 10. , 0. ])

arrA = np.array(arrA)
arrB = np.array(arrB)
arrC = np.array(arrC)

data_arrays = (arrA, arrB, arrC)

X, Y, Z = data_arrays


#ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, cmap='inferno')


c = np.abs(color)
cmhot = plt.get_cmap("hot")
ax.scatter(X, Y, Z, color, s=50, c=c, cmap=cmhot)

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
plt.show()

/ .txt 文件

0. , 10. , 20. , 30. , 40. , 50. , 60. , 50. , 40. , 30. , 20. , 10. , 0.
10. , 20. , 30. , 40. , 50. , 60. , 50. , 60. , 50. , 40. , 30. , 20. , 10.
20. , 30. , 40. , 50. , 60. , 50. , 40. , 50. , 60. , 50. , 40. , 30. , 10.
40. , 50. , 60. , 50. , 40. , 30. , 20. , 30. , 40. , 50. , 60. , 50. , 40.
60. , 50. , 40. , 30. , 20. , 10. , 0. , 10. , 20. , 30. , 40. , 50. , 60.
#... etc.

/ 错误:

KeyError                                  Traceback (most recent call last)
c:\users\te291095\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    165     try:
--> 166         rgba = _colors_full_map.cache[c, alpha]
    167     except (KeyError, TypeError):  # Not in cache, or unhashable.

KeyError: (nan, None)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-26-8ef706d1f4cb> in <module>()
     31 
     32 # parse good sensor data from imported data
---> 33 color = mpl.colors.to_rgba_array(data_file[:,0], alpha=None)
     34 #color = data_file[:,0]
     35 # display the first 16 sensor rows

c:\users\te291095\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\colors.py in to_rgba_array(c, alpha)
    265     result = np.empty((len(c), 4), float)
    266     for i, cc in enumerate(c):
--> 267         result[i] = to_rgba(cc, alpha)
    268     return result
    269 

c:\users\te291095\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\colors.py in to_rgba(c, alpha)
    166         rgba = _colors_full_map.cache[c, alpha]
    167     except (KeyError, TypeError):  # Not in cache, or unhashable.
--> 168         rgba = _to_rgba_no_colorcycle(c, alpha)
    169         try:
    170             _colors_full_map.cache[c, alpha] = rgba

c:\users\te291095\appdata\local\programs\python\python36-32\lib\site-packages\matplotlib\colors.py in _to_rgba_no_colorcycle(c, alpha)
    217         # float)` and `np.array(...).astype(float)` all convert "0.5" to 0.5.
    218         # Test dimensionality to reject single floats.
--> 219         raise ValueError("Invalid RGBA argument: {!r}".format(orig_c))
    220     # Return a tuple to prevent the cached value from being modified.
    221     c = tuple(c.astype(float))

ValueError: Invalid RGBA argument: nan

/ 可验证:

代码应该从文件中读取数据并将其处理为散点图中点的颜色。

如果您在没有文件的情况下手动读取三行并将其保存为数组,则它可以工作(见下图),所以当我从文件中获取数据时,我不明白为什么它不起作用。

它应该显示什么

您报告的问题是: mpl.colors.to_rgba_array需要一个 Matplotlib 颜色值数组,而不是浮点数。

看看这里: https : //matplotlib.org/api/colors_api.html#module-matplotlib.colors

并查看以下堆栈溢出帖子: 如何使用 matplotlib 的颜色图将数字映射到颜色?

您可以通过使用以下内容更改它来修复它(请注意我选择的任意 vmin 和 vmax 值):

norm = mpl.colors.Normalize(vmin=0, vmax=60)
cmap = cm.hot
m = cm.ScalarMappable(norm=norm, cmap=cmap)
map_to_color = np.vectorize(m.to_rgba)

# parse good sensor data from imported data
color = map_to_color(data_file[:, 0])

您发布的样本还存在关于传递给ax.scatter的维度的其他问题,但我相信您可以自己快速解决这个问题。

编辑:

在查看更多 matplotlib.pyplot.scatter 之后( https://matplotlib.org/api/_as_gen/matplotlib.pyplot.scatter.html ),这是让您的示例工作的最快方法。

删除故障线路:

color = mpl.colors.to_rgba_array(data_file[:,0], alpha=None)

并替换块:

c = np.abs(color)
cmhot = plt.get_cmap("hot")
ax.scatter(X, Y, Z, color, s=50, c=c, cmap=cmhot)

和:

values = data_file[:4, 0]
ax.scatter(X, Y, Z, c=values, cmap="hot")

data_file[:4, 0]而不是data_file[:, 0]是为了确保输入 x 和 y (n=4) 的维度与传递给c的颜色/值的维度匹配(也应该是长度n )

感谢@stakka的回答。 现在我缩短了代码并删除了所有不需要的东西。 它现在看起来像这样并且工作正常:

import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np

# set up a figure
fig = plt.figure(figsize=plt.figaspect(1))

# add the projection
ax = fig.add_subplot(1, 1, 1, projection='3d')

# load the data file
data_file = np.genfromtxt('data_file_noarr.txt', delimiter=',')

arrA = ([[0],[2],[4],[0],[2],[4],[0],[2],[4]])
arrB = ([[0],[0],[0],[2],[2],[2],[4],[4],[4]])

arrA = np.array(arrA)
arrB = np.array(arrB)

#          <-- Lowest Plot to Highest Plot loop -->
#################################################################

count = 0
cmhot = plt.get_cmap("hot")

while count < 10:
    values = data_file[0:9, count]
    arrC = np.full((9, 1), count)
    arrC = np.array(arrC)
    data_arrays = (arrA, arrB, arrC)
    X, Y, Z = data_arrays
    ax.scatter(X, Y, Z, c=values, cmap=cmhot)
    count = count + 1

#################################################################

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
plt.show()

/ 输出:

正确的输出

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM