【问题标题】:Matplotlib eventplot - raster plot from binary valuesMatplotlib eventplot - 二进制值的光栅图
【发布时间】:2021-05-01 19:22:42
【问题描述】:

我创建了一个数据框,其中每一列都是等长的 1.0s 和 0.0s 序列。数据框中没有其他内容。我想根据这些数据创建一个光栅样式的图,其中每一列都是沿 y 轴堆叠的水平线,x 轴上的每个刻度对应一个行索引值。

但是,当我尝试执行此操作时,出现“轴 -1 超出维度 0 数组的范围”错误。此错误或非常相似的错误的其他条目似乎都与事件图无关。我认为我拥有的数据类型非常适合 eventplot(一个离散的黑色破折号,只要有 1.0,否则什么都没有),但也许我错了。

这是我尝试传递的数据框类型的玩具示例,以及我正在调用的函数:

    SP1     SP3     SP5     SP7     SP9     SP11
0   1.0     0.0     0.0     0.0     0.0     0.0
1   0.0     0.0     0.0     1.0     0.0     0.0
2   0.0     0.0     0.0     0.0     0.0     0.0
3   0.0     1.0     0.0     0.0     0.0     0.0
4   0.0     0.0     1.0     0.0     1.0     0.0
5   0.0     1.0     0.0     0.0     1.0     1.0


plt.eventplot(df, colors='black', lineoffsets=1,
                    linelengths=1, orientation='vertical')

感谢您的帮助。

编辑:如果我将我的 df 转换为 np.array 并传递它,我不再得到那个特定的错误,但我根本没有得到我正在寻找的结果。我确实在 x 轴上得到了正确的值(在我的真实数据中,这是 0-22),但是我没有将每一列数据表示为单独的行,而且我在这方面没有运气方向。

【问题讨论】:

  • 如果您希望栅格为 1 的一种颜色和 0 的另一种颜色,只需使用 imshow,可能与 aspect=auto 一起使用。
  • 这是两个问题中较小的一个,但无论如何我都会尝试 imshow ,谢谢。

标签: pandas matplotlib


【解决方案1】:

当使用eventplot 时,传递给positions 的数组需要包含每一列的行号。这是您的玩具数据的示例:

import io
import pandas as pd              # v 1.2.3
import matplotlib.pyplot as plt  # v 3.3.4

# Import data into dataframe
data = """
SP1     SP3     SP5     SP7     SP9     SP11
0   1.0     0.0     0.0     0.0     0.0     0.0
1   0.0     0.0     0.0     1.0     0.0     0.0
2   0.0     0.0     0.0     0.0     0.0     0.0
3   0.0     1.0     0.0     0.0     0.0     0.0
4   0.0     0.0     1.0     0.0     1.0     0.0
5   0.0     1.0     0.0     0.0     1.0     1.0
"""
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)

# Create series of indexes containing positions for raster plot
positions = df.apply(lambda x: df.index[x == 1])

# Create raster plot with inverted y-axis to display columns in ascending order
plt.eventplot(positions, lineoffsets=df.index, linelengths=0.75, colors='black')
plt.yticks(range(positions.index.size), positions.index)
plt.gca().invert_yaxis()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-11
    • 2015-04-15
    • 2019-01-08
    • 2018-01-03
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多