[英]Altair: adding sorting destroys chart
The following code produces a column chart in which the y
axis grows in the wrong direction.以下代码生成一个柱形图,其中
y
轴以错误的方向增长。
alt.Chart(df).mark_line().encode(
x = alt.X('pub_date', timeUnit='month'),
y = alt.Y('sum(has_kw)', ),
)
I wanted to correct it as suggested by https://stackoverflow.com/a/58326269 , and changed my code to我想按照https://stackoverflow.com/a/58326269的建议更正它,并将我的代码更改为
alt.Chart(df).mark_line().encode(
x = alt.X('pub_date', timeUnit='month'),
y = alt.Y('sum(has_kw)', sort=alt.EncodingSortField('y', order='descending') ),
)
But now altair produces a strange diagram, see 2 .但现在 altair 生成了一个奇怪的图表,请参见2 。
That is, sum(has_kw)
is calculated wrong.即
sum(has_kw)
计算错误。 Why this, and how to correct it?为什么会这样,以及如何纠正?
It is hard to know exactly without seeing a sample of your data but you could try one of the following (based on the example you linked).如果没有看到您的数据样本,很难确切知道,但您可以尝试以下方法之一(基于您链接的示例)。 This first approach is similar to what you tried already:
第一种方法类似于您已经尝试过的方法:
import altair as alt
import numpy as np
import pandas as pd
# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(0, 3), range(0, 3))
z = x ** 2 + y ** 2
# Convert this grid to columnar data expected by Altair
source = pd.DataFrame({
'x': x.ravel(),
'y': y.ravel(),
'z': z.ravel()
})
alt.Chart(source).mark_rect().encode(
x='x:O',
y=alt.Y('y:O', sort='descending'),
color='z:Q'
)
This second approaches simply reverses the axes without sorting it and might be more compatible with your data:第二种方法只是反转轴而不对其进行排序,并且可能与您的数据更兼容:
alt.Chart(source).mark_rect().encode(
x='x:O',
y=alt.Y('y:O', scale=alt.Scale(reverse=True)),
color='z:Q'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.