首页 > 解决方案 > 用笑脸绘制图表百分比

问题描述

我想添加一个基于笑脸的绘图图,如下所示:dat will come from a dataframe pandas:dataframe.value_counts(normalize=True)

在此处输入图像描述

谁能给我一些线索。

标签: pandasplotly-dash

解决方案


  • 以正常方式对热图使用色阶
  • 使用annotation_text将表情符号分配给一个值
import plotly.figure_factory as ff
import plotly.graph_objects as go
import pandas as pd
import numpy as np


df = pd.DataFrame([[j*10+i for i in range(10)] for j in range(10)])

e=["","","","☹️"]

fig = go.Figure(ff.create_annotated_heatmap(
    z=df.values, colorscale="rdylgn", reversescale=False,
    annotation_text=np.select([df.values>75, df.values>50, df.values>25, df.values>=0], e),
))


fig.update_annotations(font_size=25)
# allows emoji to use background color
fig.update_annotations(opacity=0.7) 

在此处输入图像描述

更新彩色表情符号

  • 从根本上说,您需要可以接受颜色样式的表情符号
  • 为此,我切换到了 Font Awesome。这还需要切换到dashplotly的表弟,以便可以使用外部 CSS(使用 FA)
  • 然后构建一个破折号HTML 表格,应用样式逻辑来选择表情和颜色
from jupyter_dash import JupyterDash
import dash_html_components as html
import pandas as pd
import branca.colormap

# Load Data
df = pd.DataFrame([[j*10+i for i in range(10)] for j in range(10)])

external_stylesheets = [{
    'href': 'https://use.fontawesome.com/releases/v5.8.1/css/all.css',
    'rel': 'stylesheet', 'crossorigin': 'anonymous',
    'integrity': 'sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf',
    }]

# possibly could use a a different library for this - simple way to map a value to a colormap
cm = branca.colormap.LinearColormap(["red","yellow","green"], vmin=0, vmax=100, caption=None)

def mysmiley(v):
    sm = ["far fa-grin", "far fa-smile", "far fa-meh", "far fa-frown"]
    return html.Span(className=sm[3-(v//25)], style={"color":cm(v),"font-size": "2em"})

# Build App
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
    html.Table([html.Tr([html.Td(mysmiley(c)) for c in r]) for r in df.values])
])

# Run app and display result inline in the notebook
app.run_server(mode='inline')

在此处输入图像描述


推荐阅读