【发布时间】:2019-06-25 00:00:03
【问题描述】:
是否可以在 Altair 图表中按照图表 x 和 y 变量的度量单位绘制线条和几何形状?图表可能是刻面的,形状和线条取决于每个特定刻面中的数据。
一个可重现的例子:
import pandas as pd
import numpy as np
import altair as alt
alt.renderers.enable('notebook')
# make some data to test
N = 1000
df = pd.DataFrame({
'x1': np.random.normal(0, 1, N),
'x2': np.random.normal(0, 1, N),
'facet': np.random.choice(list('ABCDEFGHI'), N),
})
# derived variables
df['y1'] = np.where(np.sqrt(df['x1']**2 + df['x2']**2) > 2, 'F', 'P')
df['y2'] = 0.5*df['x2'] + 2.0 + np.random.normal(0, .5, N)
df['color'] = np.where(df['y1'].eq('F'), 'red', 'green')
# custom color map
domain = ['F', 'P']
range_ = ['red', 'green']
# create and render the chart
p1 = alt.Chart(df).mark_circle(opacity=1, size=15).encode(
alt.X('x1', scale=alt.Scale(domain=(-4, 4))),
alt.Y('x2', scale=alt.Scale(domain=(-4, 4))),
color=alt.Color('y1', scale=alt.Scale(domain=domain, range=range_)),
facet='facet'
)
# set some additional properties
p1.properties(width=150, height=150, columns=3).resolve_scale()
产生以下输出:
Q1:是否可以在每个图表中绘制一个以 0、0 为中心、半径为 2 的圆,如第二个方面所示?
圆形度量单位与 x 和 y 度量单位相同。在这种情况下,x 和 y 可以表示物理线性测量,其中每个像素的长度在 x 和 y 中是一致的。即它可能是一个飞镖板。
类比可能是 R lattice xyplot aspect = 'iso'。在此处查看方面描述:https://rdrr.io/cran/lattice/man/xyplot.html
Q2:是否可以在图表的一个角落添加一个文本注释来计算每个图表中“F”(红色)的数量?
Q3:对于轴不是“iso”并且具有不同测量单位的情况,是否可以绘制一条线和椭圆(例如,95% 密度的椭圆),如下面的第二个方面所示?也许在图表上标注了拟合线的斜率和截距?
例子:
# create and render the chart
p1 = alt.Chart(df).mark_point().encode(
x='x2',
y='y2',
facet='facet'
)
# set some additional properties
p1.properties(width=150, height=150, columns=3).resolve_scale()
在 R Lattice 中,这些类型的可视化是通过使用“aspect”、一些特定的格/网格函数以及在某些情况下编写自定义“面板”(构面)函数来实现的,该函数可以访问数据的索引在每个方面,并且可以在每个方面运行线性模型并显示结果。
【问题讨论】:
标签: python geometry facet ellipse altair