具有 NaN 和 cmap 颜色矩阵的 matplotlib 散点图

问题描述 投票:0回答:1

嗨,我有一个简单的 3D 散点图 - 一个数据框

bm
,其中列和索引作为
x
y
轴。当我绘制它时,我想添加一个颜色图 - 也很简单,我已经在下面完成了。

但是,在我的数据中

bm
我有一些我不想绘制的零 - 这也很容易 - 我将它们设置为
NaN
但是,这会导致颜色矩阵出现问题。
scatter
不喜欢这样。我尝试过使用 nan 和不使用 nan 传递颜色矩阵,但它们都失败并出现错误。

如果删除它将绘制的行

bm = bm.replace({0: np.nan})
,下面的代码将完全正常工作。

N = 100

bm = pd.DataFrame(
    index=pd.bdate_range(start='2012-01-01', periods=N, freq='B'), 
    data={x: np.random.randn(N) for x in range(1, 11)}
)

# Simulate some zeros
bm = pd.DataFrame(index=bm.index, columns=bm.columns, data=np.where(np.abs(bm.values) < 0.02, 0, bm.values))

# Set zeros to Nan so that I don't plot them
bm = bm.replace({0: np.nan})

z = bm.values
x = bm.columns.tolist()
y = bm.reset_index().index.tolist()
x, y = np.meshgrid(x, y)

# Set up plot
fig = plt.figure(figsize = (15,10))
ax = plt.axes(projection ='3d')

# plotting
ax.scatter(x, y, z, '.', c=bm.values, cmap='Reds')  # THIS FAILS

ax.xaxis.set_ticklabels(bm.columns);
ax.yaxis.set_ticklabels(bm.index.strftime('%Y-%m-%d'));

欢迎任何帮助

python matplotlib plot
1个回答
0
投票

不是 100% 确定为什么会失败,但我想这可能与

c
由于其 2D 性质而被错误地识别为 RGB/RGBA 数组有关?

来自文档:

c:颜色、序列或颜色序列,可选 标记颜色。可能的值:

  • 单色格式字符串。
  • 长度为 n 的颜色序列。
  • 使用 cmap 和norm 将 n 个数字映射到颜色的序列。
  • 行为 RGB 或 RGBA 的 2D 数组。

如果在绘图之前将数据和坐标转换为一维,则 scatter 似乎可以很好地处理 nan...

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


N = 100

bm = pd.DataFrame(
    index=pd.bdate_range(start='2012-01-01', periods=N, freq='B'), 
    data={x: np.random.randn(N) for x in range(1, 11)}
)

# Simulate some zeros
bm = pd.DataFrame(index=bm.index, columns=bm.columns, data=np.where(np.abs(bm.values) < 0.02, 0, bm.values))

# Set zeros to Nan so that I don't plot them
bm = bm.replace({0: np.nan})

# unstack dataframe
flat_bm = bm.reset_index(drop=True).unstack()
x = flat_bm.index.get_level_values(0)
y = flat_bm.index.get_level_values(1)
z = flat_bm.values


# Set up plot
fig = plt.figure(figsize = (15,10))
ax = plt.axes(projection ='3d')

# plotting
ax.scatter(x, y, z, '.', c=flat_bm.values, cmap='Reds')

ax.xaxis.set_ticklabels(bm.columns);
ax.yaxis.set_ticklabels(bm.index.strftime('%Y-%m-%d'));
© www.soinside.com 2019 - 2024. All rights reserved.