在 Pandas 中绘制二进制矩阵

Dig*_*ogy 4 python plot matplotlib matrix pandas

我在 Pandas 中有一个数据框(数据),它有一个日期时间索引(大约 25.000 天的数据)和 527 列 ID。

                  work_id_10  work_id_100  work_id_1007  work_id_1009
concert_date
1917-01-27             0            0             0             0
1917-01-28             0            0             0             0
1917-01-29             0            0             0             0
1917-01-30             0            0             0             0
1917-01-31             0            0             0             0
Run Code Online (Sandbox Code Playgroud)

每个列 ID 用 0(不存在)或 1(存在)指示特定 ID 的存在或不存在。所以,基本上我所拥有的是一个二进制值矩阵。

我现在想创建一个图,该图在 x 轴上包含所有日期,并且对于每个列 ID,将存在作为点。我正在使用 ipython。

%matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_yticklabels(data.index)
ax.set_xticklabels(data.columns)
plt.imshow/data, cmap='Greys', interpolation='none')
Run Code Online (Sandbox Code Playgroud)

这给了我一个 MemoryError:

Traceback (most recent call last):
  File "C:\Python27\Lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Python27\Lib\lib-tk\Tkinter.py", line 533, in callit
    func(*args)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", lin
e 365, in idle_draw
    self.draw()
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", lin
e 349, in draw
    FigureCanvasAgg.draw(self)
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line
469, in draw
    self.figure.draw(self.renderer)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 59, in draw_wr
apper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1079, in draw
    func(*args)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 59, in draw_wr
apper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\axes\_base.py", line 2092, in d
raw
    a.draw(renderer)
  File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 59, in draw_wr
apper
    draw(artist, renderer, *args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\image.py", line 367, in draw
    self._draw_unsampled_image(renderer, gc)
  File "C:\Python27\lib\site-packages\matplotlib\image.py", line 321, in _draw_u
nsampled_image
    self._get_unsampled_image(self._A, extent_in_ic, viewLim_in_ic)
  File "C:\Python27\lib\site-packages\matplotlib\image.py", line 219, in _get_un
sampled_image
    x = (x * 255).astype(np.uint8)
MemoryError
Run Code Online (Sandbox Code Playgroud)

这是正确的方法,为什么我会收到 MemoryError?

谢谢!

Sco*_*ott 7

正如我在评论中提到的,您可能希望将数据分解为视觉上更容易消化的块。这是一个大小为 527 x 2500 的随机矩阵的示例(1s 是蓝色,0s 是白色):

大随机矩阵

您的数据很可能具有更多结构,但可能仍然难以解释。您所描述的矩阵是 527 x 25000。您可以按年份 (527 x 365) 或按十年 (527 x 3650ish) 显示,或者四处看看哪种效果最好。

这是我将如何显示您的数据矩阵(这是一个小得多的集合):

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

data = pd.read_csv('concertdata.csv')
print data
Run Code Online (Sandbox Code Playgroud)

这会打印我的假数据:

  concert_date  work_id_10  work_id_100  work_id_1007  work_id_1009  \
0   1917-01-27           1            1             0             0   
1   1917-01-28           0            0             1             0   
2   1917-01-29           0            1             1             0   
3   1917-01-30           1            0             0             0   
4   1917-01-31           0            0             0             0   
5   1917-02-01           0            0             1             1   

   work_id_1011  
0             0  
1             0  
2             1  
3             1  
4             1  
5             0  
Run Code Online (Sandbox Code Playgroud)

然后获取标题和值:

id_labels = data.columns[1:]
# take the transpose since you want to see id on y-axis
id_matrix = np.array(data[id_labels].values, dtype=float).T
concert_dates = pd.to_datetime(data['concert_date'])
concert_dates = [d.date() for d in concert_dates]
Run Code Online (Sandbox Code Playgroud)

现在使用 imshow() 绘制此图:

fig, ax = plt.subplots()
mat = ax.imshow(id_matrix, cmap='GnBu', interpolation='nearest')
plt.yticks(range(id_matrix.shape[0]), id_labels)
plt.xticks(range(id_matrix.shape[1]), concert_dates)
plt.xticks(rotation=30)
plt.xlabel('Concert Dates')

# this places 0 or 1 centered in the individual squares
for x in xrange(id_matrix.shape[0]):
    for y in xrange(id_matrix.shape[1]):
        ax.annotate(str(id_matrix[x, y])[0], xy=(y, x), 
                    horizontalalignment='center', verticalalignment='center')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您可以四处玩耍以使其更漂亮,但这是总体思路。