python - 自定义 matplotlib 图 : chess board like table with colored cells

标签 python matplotlib pandas

随着我学习 python 和这个有趣的绘图库,我开始使用 matplotlib 渲染绘图。我需要有关我正在处理的问题的自定义图的帮助。可能已经有一个内置的功能。

问题: 我正在尝试绘制一个表格(矩形)作为具有 96 个单独单元格(8 行 X 12 列)的图。用特定颜色为每个备选单元格着色(如棋盘:我将使用其他一些颜色组合而不是黑色/白色),并从 Pandas 数据框或 Python 字典中为每个单元格插入值。在侧面显示列和行标签。

示例数据:http://pastebin.com/N4A7gWuH

我希望情节看起来像这样用 numpy/pandas ds 中的单元格中的值替换。

样本图:http://picpaste.com/sample-E0DZaoXk.png

感谢您的意见。

PS: 确实在 mathplotlib 的邮件列表上发布了同样的内容

最佳答案

基本上,您可以只使用imshowmatshow

但是,我不是很清楚你的意思。

如果您想要一个棋盘,每个“白色”单元格都由其他矢量着色,您可以这样做:

import matplotlib.pyplot as plt
import numpy as np

# Make a 9x9 grid...
nrows, ncols = 9,9
image = np.zeros(nrows*ncols)

# Set every other cell to a random number (this would be your data)
image[::2] = np.random.random(nrows*ncols //2 + 1)

# Reshape things into a 9x9 grid.
image = image.reshape((nrows, ncols))

row_labels = range(nrows)
col_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
plt.matshow(image)
plt.xticks(range(ncols), col_labels)
plt.yticks(range(nrows), row_labels)
plt.show()

enter image description here

显然,这只适用于行数和列数为奇数的情况。对于行数和列数为偶数的数据集,您可以遍历每一行。

例如:

for i, (image_row, data_row) in enumerate(zip(image, data)):
    image_row[i%2::2] = data_row

但是,每行中“数据”单元格的数量会有所不同,这是我对您的问题定义感到困惑的地方。

根据定义,棋盘图案的每一行中都有不同数量的“白色”单元格。
您的数据大概(?)在每一行中具有相同数量的值。你需要定义你想做什么。您可以截断数据,或添加额外的列。

编辑:我刚刚意识到这仅适用于奇数长度的列。

无论如何,我仍然对您的问题感到困惑。

您想要一个“完整”的数据网格并且想要将数据网格中的值的“棋盘”模式设置为不同的颜色,还是想要“散布”您的具有“棋盘”模式的值绘制为某种恒定颜色的数据?

更新

听起来您想要更像电子表格的东西? Matplotlib 对此并不理想,但您可以做到。

理想情况下,您只需使用 plt.table,但在这种情况下,直接使用 matplotlib.table.Table 会更容易:

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

from matplotlib.table import Table

def main():
    data = pandas.DataFrame(np.random.random((12,8)), 
                columns=['A','B','C','D','E','F','G','H'])
    checkerboard_table(data)
    plt.show()

def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(data):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

        tb.add_cell(i, j, width, height, text=fmt.format(val), 
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text=label, loc='right', 
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center', 
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    return fig

if __name__ == '__main__':
    main()

enter image description here

关于python - 自定义 matplotlib 图 : chess board like table with colored cells,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194482/

相关文章:

python - 如何使循环运行到不再​​有意义的时候?

python - Pandas:字符串的多个条件

python - 对 pandas 系列中的多索引级别求和

python - 确定子字符串在 Python 中的字符串中出现的次数

python - 在 Python 中定义一个引用 self 而不是 'self' 的类方法是否有用?

python - matplotlib 中默认的随机颜色

python - 线条不显示在条形图上

python - 线性判别分析后仅绘制了 2 个簇,而不是 3 个

python - 使用 pandas 查找是否有两列名称不同但值相同

Python-原始文本到字典列表