有条件地更改特定单元格的背景颜色 [英] Conditionally change background color of specific cells

查看:106
本文介绍了有条件地更改特定单元格的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame,可以将其另存为png文件.但是现在我想更改满足特定条件的特定细胞的背景颜色.

I have a DataFrame and I can save it as a png file. But now I want to change the background color of specific cells who meet a certain condition.

条件:

  • 80岁或以上的数字必须具有绿色背景.
  • 低于80的数字必须带有红色背景.
  • 所有列名称和索引单元格都需要带有白色文本颜色的黑色背景.

以下帖子接近我想要的内容,但没有提供我需要的答案. ​​帖子1 帖子2

The following posts came close to what I want but didn't provided with the answer I needed. Post 1 Post 2

我的代码:

import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import pandas as pd

#My dataframe
df = pd.DataFrame({
    'Weeks' : [201605, 201606, 201607, 201608],
    'Computer1' : [50, 77, 96, 100],
    'Computer2' : [50, 79, 100, 80],
    'Laptop1'   : [75, 77, 96, 95],
    'Laptop2'   : [86, 77, 96, 40],
    'Phone'     : [99, 99, 44, 85],
    'Phone2'    : [93, 77, 96, 25],
    'Phone3'    : [94, 91, 96, 33]
})
df2 = df.set_index('Weeks') #Makes the column 'Weeks' the index.

#Make a png file out of an dataframe.
plt.figure(figsize=(9,3))
ax = plt.subplot(211, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis
table(ax, df2, rowLabels=df2.index, colLabels=df2.columns, loc='center', cellColours=None)
plt.savefig('mytable.png') #save it as an png.

当前外观如下:

这就是我想要的样子

推荐答案

您可以执行以下操作:

colors = df2.applymap(lambda x: 'green' if x>= 80 else 'red').reset_index().drop(['Weeks'], axis=1)


tbl = table(ax, df2, loc='center',
            cellColours=colors.as_matrix(),
            colColours=['black']*len(colors.columns),
            rowColours=['black']*len(colors))

设置索引的颜色:

[tbl._cells[row, -1]._text.set_color('white') for row in range(1, len(colors)+1)]

设置标题的颜色:

[tbl._cells[0, col]._text.set_color('white') for col in range(len(colors.columns))]
plt.show()

代码(完整):

import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import pandas as pd

#My dataframe
df = pd.DataFrame({
    'Weeks' : [201605, 201606, 201607, 201608],
    'Computer1' : [50, 77, 96, 100],
    'Computer2' : [50, 79, 100, 80],
    'Laptop1'   : [75, 77, 96, 95],
    'Laptop2'   : [86, 77, 96, 40],
    'Phone'     : [99, 99, 44, 85],
    'Phone2'    : [93, 77, 96, 25],
    'Phone3'    : [94, 91, 96, 33]
})
df2 = df.set_index('Weeks') #Makes the column 'Weeks' the index.

colors = df2.applymap(lambda x: 'green' if x>= 80 else 'red') \
        .reset_index().drop(['Weeks'], axis=1)

#print(colors)

plt.figure(figsize=(10,5))

ax = plt.subplot(2, 1, 1, frame_on=True) # no visible frame

#ax.xaxis.set_visible(False)    # hide the x axis
#ax.yaxis.set_visible(False)    # hide the y axis

# hide all axises
ax.axis('off')

# http://matplotlib.org/api/pyplot_api.html?highlight=table#matplotlib.pyplot.table
tbl = table(ax, df2,
            loc='center',
            cellLoc='center',
            cellColours=colors.as_matrix(),
            colColours=['black']*len(colors.columns),
            rowColours=['black']*len(colors),
            #fontsize=14
      )


# set color for index (X, -1) and headers (0, X)
for key, cell in tbl.get_celld().items():
    if key[1] == -1 or key[0] == 0:
        cell._text.set_color('white')
    # remove grid lines
    cell.set_linewidth(0)

# refresh table
plt.show()

# save it as an png.
plt.savefig('mytable.png')

这篇关于有条件地更改特定单元格的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆