julia - Vega-Lite - 多个数据集的一个图

标签 julia legend altair vega-lite

我正在为 Julia 开发一个包,目标是使用 Vega-Lite 作为后端进行快速绘图。 熟悉 Matplotlib 的人都知道,使用不同的向量集并将所有向量绘制在同一张图中,每个向量都有自己的标签是很常见的。例如:

x = range(0,10)
y = np.random.rand(10)
w = range(0,5)
z = np.random.rand(5)
plt.plot(x,y,label = 'y')
plt.plot(w,z,label = 'z')
plt.legend()

Plot from code

我想知道如何使用 Vega-Lite(或 Altair)做类似的事情。 我知道我可以做两个单独的情节,然后将一个叠加在另一个之上。我的问题主要是关于如何让传说发挥作用,因为要获得传说,通常需要另一个领域 例如“颜色”,指向数据框中的另一个字段。

我看过类似的帖子,但处理的是从不同列发布数据的问题。这种情况的答案基本上是使用折叠变换。但在我的问题中,这不太有效,因为我更感兴趣的是从两个不同的图开始,可能使用两个不同的数据集,所以“合并”数据集不是一个好的解决方案。

最佳答案

您可以利用在复合图表中,Vega-Lite 默认使用共享比例这一事实。如果您将颜色、形状、strokeDash 等分配给每个图层的唯一值,则会自动生成适当的图例。

这是一个例子,使用 Altair 生成 Vega-Lite 规范:

import pandas as pd
import numpy as np
import altair as alt

x = np.linspace(0, 10)

df1 = pd.DataFrame({
    'x': x,
    'y': np.sin(x)
})
df2 = pd.DataFrame({
    'x': x,
    'y': np.cos(x)
})

chart1 = alt.Chart(df1).transform_calculate(
    label='"sine"'
).mark_line().encode(
    x='x',
    y='y',
    color='label:N'
)

chart2 = alt.Chart(df2).transform_calculate(
    label='"cosine"'
).mark_line().encode(
    x='x',
    y='y',
    color='label:N'
)

alt.layer(chart1, chart2)

enter image description here

关于julia - Vega-Lite - 多个数据集的一个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64436996/

相关文章:

python - 在 python 中水平对齐条形图图例

python - 运行matplotlib绘图标签,然后显示错误框

python - 如何在 Altair 的 HConcatChart 中配置图表位置

julia - 从文件中读取输入的更简单方法

oop - Julia - 检查对象是否具有属性

macros - 从基础扩展 `@show`

python - 在 Altair 的每个方面子图中显示 x 和 y 标签

julia - 关于项目.toml

python - 更改图例中椭圆 handle 的形状

python - Altair 默认调色板颜色(十六进制)