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

你。 提交于 2020-08-10 18:51:58

问题


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)

回答1:


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
)



来源:https://stackoverflow.com/questions/62904614/altair-how-to-show-a-dataframe-column-as-label-with-its-respective-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!