Altair-如何将数据框列显示为带有相应颜色的标签 [英] Altair - how to show a dataframe column as label with its respective color
本文介绍了Altair-如何将数据框列显示为带有相应颜色的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在面积图上显示我从数据框中选择的列名称作为标签,以及使用Altair时的相应颜色。
I am trying to show on an Area Chart the column name(s) I selected from a Dataframe as label, along with its respective color using Altair.
问题是,每个这样做的时候,图表消失了,我无法根据十六进制代码列表自定义颜色。
The problem is that every time I do it, the chart disappear and I can't customize the colors based on a list of hex Codes.
有什么方法可以实现这一目标?
Is there any way to achieve this?
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)
推荐答案
图表使用颜色编码消失的原因是,每个颜色组仅包含一个点,并且该点下的区域的宽度为零,因此显示为空。
The reason the chart disappears with a color encoding is because your color groups each contain only a single point, and the area under a point has zero width and thus appears empty. Perhaps a bar chart would be a better fit?
chart = alt.Chart(df).mark_bar().encode(
x=xSelected,
y=ySelected[0],
color=alt.Color(f'{xSelected}:N'),
tooltip=ySelected
)
这篇关于Altair-如何将数据框列显示为带有相应颜色的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文