【问题标题】:Python .txt file with numbers to rgba带有数字到 rgba 的 Python .txt 文件
【发布时间】:2019-03-04 03:55:54
【问题描述】:

有人可以帮我完成我的项目吗? 我想通过数据记录器将来自几个温度传感器的数据保存到文件中,然后使用 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

/ 可验证:

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

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

【问题讨论】:

  • Es tut mir Leid, dass der Code nicht sehr übersichtlich ist, aber ich habe halt schon viele mögliche Lösungen ausprobiert / 很抱歉代码不是很清楚,但我已经尝试了很多可能的解决方案
  • 与其为发布您的完整代码而道歉,并且只是模糊地描述您想要获得什么样的可视化想法,我建议您将帖子缩短失败的代码部分的示例。同样重要的是,请尽可能具体且准确地描述您期望的结果。我认为没有人知道您所说的“交互式 3d 地图”是什么意思,抱歉:不,您想要什么并不明显。造成这种情况的主要原因是,您可能已经考虑了数小时或数天,并且心中有一个特定的想法 - 但我们没有。
  • 为了给您一个很好的答案,如果您还没有看过How to Ask,它可能会对我们有所帮助。如果您可以提供minimal reproducible example,它可能也很有用。
  • 我不明白你为什么要在这里使用to_rbga_array 或类似的功能。在我看来,你可以直接ax.scatter(X, Y, Z, s=50, c=data_file[:,0], cmap="hot")

标签: python arrays matplotlib 3d


【解决方案1】:

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

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

还请查看以下堆栈溢出帖子: How to map number to color using matplotlib's colormap?

您可以通过以下方式更改它来修复它(请注意我选择的任意 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 的颜色/值相匹配(长度也应该是 @ 987654333@)

【讨论】:

  • 感谢您的快速回答。我会尽快修复并报告。
  • 我试图在我的代码中实现它,但我仍然得到错误,它不会处理数组。 unhashable type: 'numpy.ndarray' 现在有一个新错误:c of shape (4, 16, 13) not accepted as a color sequence for x with size 13, y with size 13 我把 color = map_to_color(data_file[:, 0]) 改成了 color = map_to_color(data_file[:, 0:13]) 这样对吗?会不会是 np.abs() 有问题?
  • 我已经编辑了我的答案,让您获得一个快速、完整的工作解决方案。
  • 非常感谢。现在可以了。很抱歉再次打扰您,但只是一个简短的问题...您知道在哪里可以找到一种不使背景中的散点几乎透明的方法吗?
  • 只需将alpha=1 添加到分散调用中:ax.scatter(X, Y, Z, c=values, alpha=1, cmap="hot")
【解决方案2】:

感谢@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()

/输出:

【讨论】:

  • 回答您关于透明点的问题:您可以通过将 alpha=1 传递给 matplotlib.pyplot.scatter 调用来避免这种情况。我还想提一下,如果您知道所需迭代的确切数量,您应该使用 for 循环而不是 while 循环。只需写:for count in range(10):
  • 是的。谢谢。我不习惯 for 语法,所以我只使用了 while。但是感谢您对透明度的修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多