我开始使用matplotlib渲染绘图,因为我学习了python和这个有趣的绘图库。对于我正在处理的问题,我需要帮助自定义绘图。可能已经有了内置功能。</ p>
问题: 我试图绘制一个表(矩形)作为一个96个单元格(8行X 12 cols)的图。使用特定颜色为每个替代单元着色(如棋盘:而不是黑/白我会使用其他颜色组合)并从pandas数据框或python字典中为每个单元插入值。在侧面显示col和row标签。
示例数据:http://pastebin.com/N4A7gWuH
我希望情节看起来像这样用numpy / pandas ds代替单元格中的值。
示例图:http://picpaste.com/sample-E0DZaoXk.png
感谢您的意见。
PS:在mathplotlib的邮件列表上发布了相同的内容
答案 0 :(得分:31)
基本上,您可以使用imshow
或matshow
。
但是,我不太清楚你的意思。
如果你想要一个棋盘上的每个“白色”单元格被其他一些矢量着色,你可以这样做:
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()
显然,这仅适用于具有奇数行和列的事物。您可以遍历具有偶数行和列的数据集的每一行。
E.g:
for i, (image_row, data_row) in enumerate(zip(image, data)):
image_row[i%2::2] = data_row
但是,每行中“数据”单元格的数量会有所不同,这就是我对问题定义感到困惑的地方。
根据定义,棋盘图案在每一行中都有不同数量的“白色”单元格。
您的数据可能(?)在每行中具有相同数量的值。您需要定义您想要做的事情。您可以截断数据,也可以添加额外的列。
编辑:我刚才意识到这只适用于奇数列的数据。
无论如何,我仍然对你的问题感到困惑。
你想要一个“完整”的数据网格,并希望将数据网格中值的“棋盘”模式设置为不同的颜色,或者你想要“穿插”你的带有“棋盘格”值的数据被绘制成一些恒定的颜色?
听起来你想要更像spreasheet的东西? 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()