【问题标题】:How to assign specific colors to specific cells in a Matplotlib table?如何为 Matplotlib 表中的特定单元格分配特定颜色?
【发布时间】:2018-03-21 16:39:14
【问题描述】:

按照 pylab_examples,我在 matplotlib 中创建了一个简单的 2x5 单元格表。

代码:

# Prepare table
columns = ('A', 'B', 'C', 'D', 'E')
rows = ["A", "B"]
cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]]
# Add a table at the bottom of the axes
ax[4].axis('tight')
ax[4].axis('off')
the_table = ax[4].table(cellText=cell_text,colLabels=columns,loc='center')

现在,我想用color = "#56b5fd" 为单元格A1 着色,用color = "#1ac3f5" 为单元格A2 着色。所有其他单元格应保持白色。 Matplotlib 的 table_demo.pythis 示例仅向我展示了如何应用具有取决于单元格中值的预定义颜色的颜色图。

如何为 Matplotlib 生成的表格中的特定单元格分配特定颜色?

【问题讨论】:

    标签: python matplotlib colors


    【解决方案1】:

    @ImportanceOfBeingErnest 提供了一个很好的答案。但是,对于早期版本的 Matplotlib,第二种方法:

    the_table[(1, 0)].set_facecolor("#56b5fd")
    

    将导致 TypeError:TypeError: 'Table' object has no attribute '__getitem__' TypeError 可以通过使用以下语法来克服:

    the_table.get_celld()[(1,0)].set_facecolor("#56b5fd")
    the_table.get_celld()[(2,0)].set_facecolor("#1ac3f5")
    

    See also this example.

    (在 Matplotlib 1.3.1 上确认)

    【讨论】:

      【解决方案2】:

      为表格中的单元格背景着色的最简单方法是使用cellColours 参数。您可以提供与数据具有相同形状的列表列表或数组。

      import matplotlib.pyplot as plt
      # Prepare table
      columns = ('A', 'B', 'C', 'D', 'E')
      rows = ["A", "B"]
      cell_text = [["1", "1","1","1","1"], ["2","2","2","2","2"]]
      # Add a table at the bottom of the axes
      colors = [["#56b5fd","w","w","w","w"],[ "#1ac3f5","w","w","w","w"]]
      
      fig, ax = plt.subplots()
      ax.axis('tight')
      ax.axis('off')
      the_table = ax.table(cellText=cell_text,cellColours=colors,
                           colLabels=columns,loc='center')
      
      plt.show()
      

      或者,您可以将特定单元格的 facecolor 设置为

      the_table[(1, 0)].set_facecolor("#56b5fd")
      the_table[(2, 0)].set_facecolor("#1ac3f5")
      

      产生与上面相同的输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-14
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多