标记一个条是可行的,只需几个额外的步骤。我将使用内置的airports 数据集进行演示。
airports = data.airports().query("country == 'USA'").dropna()
airports['label'] = False # create new column
airports.loc[airports['state'] == 'NY', 'label'] = True # choose state to label in the new column
airports_bar = alt.Chart(airports).mark_bar().encode(
y=alt.Y('state:N', sort = 'x'),
x=alt.X('count()', axis=alt.Axis(grid=False)),
color=alt.Color('label', legend=None),
tooltip=['count()']
)
正如上面代码中的 cmets 中所解释的,我们只需创建一个新列,其中将包含我们要标记的条形。我选择标注NY;一旦我们创建了新列,我们只需将其值NY 设置为True。然后,这将在 color 参数中用于 color NY,与所有其他状态分开。要使用计数值标记NY,我们使用mark_text,在其中我们专门过滤/查询NY,而不是整个数据帧。这允许我们只标记NY 而不能标记其他状态。代码和绘图如下所示:
airports_bar + alt.Chart(airports.query("state == 'NY'")).mark_text(dx=10).encode(
y=alt.Y('state:N'),
x=alt.X('count()', axis=alt.Axis(grid=False)),
text='count()')
Figure with only one bar colored and labelled.
请注意,尽管在此演示中未显示,但我们应该按计数对条形图进行排序。希望这回答了你的问题!