[英]Sorting based on the alt.Color field in Altair
I am attempting to sort a horizontal barchart based on the group to which it belongs.我试图根据它所属的组对水平条形图进行排序。 I have included the dataframe, code that I thought would get me to group-wise sorting, and image.我已经包含了数据框、我认为可以让我进行分组排序的代码和图像。 The chart is currently sorted according to the species column in alphabetical order, but I would like it sorted by the group so that all "bads" are together, similarly, all "goods" are together.该图表目前按字母顺序根据物种列进行排序,但我希望它按组排序,以便所有“坏”都在一起,同样,所有“商品”都在一起。 Ideally, I would like to take it one step further so that the goods and bads are subsequently sorted by value of 'LDA Score', but that was the next step.理想情况下,我想更进一步,以便随后按“LDA 分数”的值对商品和不良品进行排序,但这是下一步。
Dataframe:
Unnamed: 0,Species,Unknown,group,LDA Score,p value
11,a,3.474929757,bad,3.07502591,5.67e-05
16,b,3.109308852,bad,2.739744898,0.000651725
31,c,3.16979865,bad,2.697247855,0.03310557
38,d,0.06730106400000001,bad,2.347746497,0.013009626000000002
56,e,2.788383183,good,2.223874347,0.0027407140000000004
65,f,2.644346144,bad,2.311106698,0.00541244
67,g,3.626001112,good,2.980960068,0.038597163
74,h,3.132399759,good,2.849798377,0.007021518000000001
117,i,3.192113412,good,2.861299028,8.19e-06
124,j,0.6140430960000001,bad,2.221483531,0.0022149739999999998
147,k,2.873671544,bad,2.390164757,0.002270102
184,l,3.003479213,bad,2.667274876,0.008129727
188,m,2.46344998,good,2.182085465,0.001657861
256,n,0.048663767,bad,2.952260299,0.013009626000000002
285,o,2.783848855,good,2.387345098,0.00092491
286,p,3.636219,good,3.094047,0.001584756
The code:编码:
bars = alt.Chart(df).mark_bar().encode(
alt.X('LDA Score:Q'),
alt.Y("Species:N"),
alt.Color('group:N', sort=alt.EncodingSortField(field="Clinical group", op='distinct', order='ascending'))
)
bars
Two things:两件事情:
The result might look something like this:结果可能如下所示:
alt.Chart(df).transform_calculate(
order='datum.group == "bad" ? 0 : 1'
).mark_bar().encode(
alt.X('LDA Score:Q'),
alt.Y("Species:N", sort=alt.SortField('order')),
alt.Color('group:N')
)
Edit : it turns out the reason sorting by group
fails is that the default operation for sort fields is sum
, which only works well on quantitative data.编辑:原来按group
排序失败的原因是排序字段的默认操作是sum
,它只适用于定量数据。 If you choose a different operation, you can sort on nominal data directly.如果您选择不同的操作,您可以直接对名义数据进行排序。 For example, this shows the correct output:例如,这显示了正确的输出:
alt.Chart(df).mark_bar().encode(
alt.X('LDA Score:Q'),
alt.Y("Species:N", sort=alt.EncodingSortField('group', op='min')),
alt.Color('group:N')
)
See vega/vega-lite#6064 for more information.有关更多信息,请参阅vega/vega-lite#6064 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.