2017-08-16 512 views
0

我有我使用此代码创建一个热图:的Python Plotly - 在热图上标注更改字体的颜色

dfreverse = df_hml.values.tolist() 
dfreverse.reverse() 

colorscale = [[0, '#FFFFFF'],[0.4, '#F8F8FF'], [1, '#F1C40F']] 

x = [threeYr,twoYr,oneYr,Yr] 
y = ['March', 'February', 'January', 'December', 'November', 'October', 'September', 'August', 'July', 'June', 'May', 'April'] 
z = dfreverse 

z_text = np.around(z, decimals=2) # Only show rounded value (full value on hover) 

fig = ff.create_annotated_heatmap(z, x=x, y=y,annotation_text=z_text, colorscale=colorscale, hoverinfo='none') 


# Altering x axis 
fig['layout']['xaxis']['tickfont']['family'] = 'Gill Sans MT' 
fig['layout']['xaxis']['tickfont']['size'] = 12 
fig['layout']['xaxis']['tickfont']['color'] = "black" 
fig['layout']['xaxis']['tickangle'] = 0 

# Altering x axis 
fig['layout']['yaxis']['tickfont']['family'] = "Gill Sans MT" 
fig['layout']['yaxis']['tickfont']['size'] = 12 
fig['layout']['yaxis']['tickfont']['color'] = "black" 
fig['layout']['yaxis']['tickangle'] = 25 

# Altering main font 
fig['layout']['font'] ["family"] = "Gill Sans MT" 
fig['layout']['font']['size'] = 9 

plotly.offline.iplot(fig,config={"displayModeBar": False},show_link=False,filename='pandas-heatmap') 

enter image description here

正如你可以看到,八月至今年3月可是没有任何数据,因此显示为0.我不能删除这个,否则热图不工作......所以我想我会改变任何0的字体为白色隐藏它们。但我不知道如何做到这一点。

我发现这个代码,改变注释的字体大小,但不知道如何改变它来改变颜色,如果值== 0(为“我”是不是值)

for i in range(len(fig.layout.annotations)): 
     fig.layout.annotations[i].font.size = 9 

回答

1

而不是更改注释只是循环访问z值,并用“”替换0值。这产生相同的输出。我已经使用一些模型数据来模拟这个问题。

代码:

import pandas as pd 
import numpy as np 
import plotly.figure_factory as ff 
import plotly.offline as py_offline 
py_offline.offline.init_notebook_mode() 
colorscale = [[0, '#FFFFFF'],[0.4, '#F8F8FF'], [1, '#F1C40F']] 

x = ['2015','2016','2017','2018'] 
y = ['March', 'February', 'January','April'] 
z = [[1,2.129,3,4], 
    [0,0,1,2], 
    [6,0,1,0], 
    [6,0,0,2]] 

z_text = [] 

for q, arr in enumerate(np.around(z, decimals=2)): 
    z_text.append([str(h) if h else "" for h in arr]) 

fig = ff.create_annotated_heatmap(z, x=x, y=y,annotation_text=z_text, colorscale=colorscale, hoverinfo='none') 


# Altering x axis 
fig['layout']['xaxis']['tickfont']['family'] = 'Gill Sans MT' 
fig['layout']['xaxis']['tickfont']['size'] = 12 
fig['layout']['xaxis']['tickfont']['color'] = "black" 
fig['layout']['xaxis']['tickangle'] = 0 

# Altering x axis 
fig['layout']['yaxis']['tickfont']['family'] = "Gill Sans MT" 
fig['layout']['yaxis']['tickfont']['size'] = 12 
fig['layout']['yaxis']['tickfont']['color'] = "black" 
fig['layout']['yaxis']['tickangle'] = 25 

# Altering main font 
fig['layout']['font'] ["family"] = "Gill Sans MT" 
fig['layout']['font']['size'] = 9 

py_offline.iplot(fig,config={"displayModeBar": False},show_link=False,filename='pandas-heatmap') 

输出: plotly annotations hide zero values

+0

嘿那仁再次:)...我将在明天早上,因为我不是在工作,但您的解决方案进行测试比我想要做的更有意义! – ScoutEU

+0

@ScoutEU无需花费时间 –

+0

经过测试。完美的作品。谢谢 :) – ScoutEU