我有一个DataFrame,我可以将其保存为png文件。但现在我想改变满足特定条件的特定细胞的背景颜色。
条件:
以下帖子接近我想要的但没有提供我需要的答案。 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.
答案 0 :(得分:4)
你可以这样做:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans....
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
设置索引的颜色:
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()