使用 altair 在 python 中突出显示条形图中的特定列
Highlighting specific columns in bar chart in python using altair
我想根据我的要求在 python 的条形图中突出显示特定数据点。使用 altair,我能够获得一个数据点的结果(例如代码中的 'A')。这是示例数据框和代码
import pandas as pd
import altair as alt
df = pd.DataFrame({
'Rank': [25, 20, 40, 10, 50, 35],
'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})
bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
x = alt.X('Name:O', sort ='x'),
color=alt.condition(
alt.datum.Name == 'A',
alt.value('red'),
alt.value('blue')
))
bar1
如何用相同的颜色突出显示两个或多个数据点(例如 A 和 B),而用不同的颜色突出显示其他数据点?我尝试将名称作为列表 Select = ['A', 'B']
传递,然后传递 alt.datum.Name == Select
但这不起作用?
我怎样才能完成这个?
另外,试图理解为什么作为列表传递不起作用?
谢谢
您可以使用 FieldOneOfPredicate
检查 Name
列是否是 列表中 项之一:
import pandas as pd
import altair as alt
df = pd.DataFrame({
'Rank': [25, 20, 40, 10, 50, 35],
'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})
bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
x = alt.X('Name:O', sort ='x'),
color=alt.condition(
alt.FieldOneOfPredicate('Name', ['A', 'B']),
alt.value('red'),
alt.value('blue')
))
bar1
您可以在 the VegaLite docs 中阅读更多相关信息。您还可以使用带有“或”运算符的两个表达式字符串:
color=alt.condition(
"datum.Name == 'A'"
"|| datum.Name == 'B'", # splitting on two rows for readability
alt.value('red'),
alt.value('blue')
)
我不认为有一个 Vega 表达式运算符可以像 Python 的 in
那样用于检查成员资格。 也没提
我想根据我的要求在 python 的条形图中突出显示特定数据点。使用 altair,我能够获得一个数据点的结果(例如代码中的 'A')。这是示例数据框和代码
import pandas as pd
import altair as alt
df = pd.DataFrame({
'Rank': [25, 20, 40, 10, 50, 35],
'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})
bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
x = alt.X('Name:O', sort ='x'),
color=alt.condition(
alt.datum.Name == 'A',
alt.value('red'),
alt.value('blue')
))
bar1
如何用相同的颜色突出显示两个或多个数据点(例如 A 和 B),而用不同的颜色突出显示其他数据点?我尝试将名称作为列表 Select = ['A', 'B']
传递,然后传递 alt.datum.Name == Select
但这不起作用?
我怎样才能完成这个? 另外,试图理解为什么作为列表传递不起作用? 谢谢
您可以使用 FieldOneOfPredicate
检查 Name
列是否是 列表中 项之一:
import pandas as pd
import altair as alt
df = pd.DataFrame({
'Rank': [25, 20, 40, 10, 50, 35],
'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
})
bar1 =alt.Chart(df).mark_bar().encode( y = alt.Y('Rank'),
x = alt.X('Name:O', sort ='x'),
color=alt.condition(
alt.FieldOneOfPredicate('Name', ['A', 'B']),
alt.value('red'),
alt.value('blue')
))
bar1
您可以在 the VegaLite docs 中阅读更多相关信息。您还可以使用带有“或”运算符的两个表达式字符串:
color=alt.condition(
"datum.Name == 'A'"
"|| datum.Name == 'B'", # splitting on two rows for readability
alt.value('red'),
alt.value('blue')
)
我不认为有一个 Vega 表达式运算符可以像 Python 的 in
那样用于检查成员资格。