繁体   English   中英

Altair - 如何将 dataframe 列显示为 label 及其各自的颜色

[英]Altair - how to show a dataframe column as label with its respective color

我试图在面积图上显示我从 Dataframe 中选择的列名,如 label,以及使用 Altair 的相应颜色。

问题是每次我这样做时,图表都会消失,我无法根据十六进制代码列表自定义 colors。

有什么办法可以做到这一点?

我需要的标签

我需要的定制颜色,可惜没有标签

import altair as alt
import pandas as pd
import os


df = {
    'Month': ['Apr', 'May'],
    'Status': ['Working', 'Complete'],
    'Revenue': [1000, 2000],
    'Profit': [500, 600]
}

df = pd.DataFrame(df)

hexList = [
    '#002664', '#72BF44', '#EED308', '#5E6A71', '#7C9DBE', '#F47920', '#1C536E', '#2D580C',
]

xSelected = 'Status'
ySelected = ['Revenue']

chartsList = []

chart = alt.Chart(df).mark_area().encode(
    x=xSelected,
    y=ySelected[0],
    #color=alt.Color(f'{xSelected}:N'), ### **==> this gives me the labels I neeed, but no chart is plotted**
    color=alt.value(f'{hexList[0]}'), ### **==> this gives me the chart with the color I want, but without the labels I need**
    tooltip=ySelected
)

mainDir = os.path.dirname(__file__)
filePath = os.path.join(mainDir, 'altairChart.html')
chart.save(filePath)

图表因颜色编码而消失的原因是每个颜色组仅包含一个点,并且点下的区域宽度为零,因此显示为空。 也许条形图会更合适?

chart = alt.Chart(df).mark_bar().encode(
    x=xSelected,
    y=ySelected[0],
    color=alt.Color(f'{xSelected}:N'),
    tooltip=ySelected
)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM