带区间选择的散点图和直方图#
此示例展示了如何将散点图和直方图关联起来,以便直方图中的区间选择将在散点图中绘制选定的值。
请注意,两个子图都需要知道由 transform_bin 方法创建的 mbin 字段。为了实现这一点,数据不传递给创建子图的 Chart() 实例,而是直接传递给连接两个图的 hconcat() 函数。
import altair as alt
import pandas as pd
import numpy as np
x = np.random.normal(size=100)
y = np.random.normal(size=100)
m = np.random.normal(15, 1, size=100)
source = pd.DataFrame({"x": x, "y":y, "m":m})
# interval selection in the scatter plot
pts = alt.selection_interval(encodings=["x"])
# left panel: scatter plot
points = alt.Chart().mark_point(filled=True, color="black").encode(
x='x',
y='y'
).transform_filter(
pts
).properties(
width=300,
height=300
)
# right panel: histogram
mag = alt.Chart().mark_bar().encode(
x='mbin:N',
y="count()",
color=alt.when(pts).then(alt.value("black")).otherwise(alt.value("lightgray"))
).properties(
width=300,
height=300
).add_params(pts)
# build the chart:
alt.hconcat(
points,
mag,
data=source
).transform_bin(
"mbin",
field="m",
bin=alt.Bin(maxbins=20)
)
import altair as alt
import pandas as pd
import numpy as np
x = np.random.normal(size=100)
y = np.random.normal(size=100)
m = np.random.normal(15, 1, size=100)
source = pd.DataFrame({"x": x, "y":y, "m":m})
# interval selection in the scatter plot
pts = alt.selection_interval(encodings=["x"])
# left panel: scatter plot
points = alt.Chart().mark_point(filled=True, color="black").encode(
x='x',
y='y'
).transform_filter(
pts
).properties(
width=300,
height=300
)
# right panel: histogram
mag = alt.Chart().mark_bar().encode(
x='mbin:N',
y="count()",
color=alt.when(pts).then(alt.value("black")).otherwise(alt.value("lightgray"))
).properties(
width=300,
height=300
).add_params(pts)
# build the chart:
alt.hconcat(
points,
mag,
data=source
).transform_bin(
"mbin",
field="m",
bin=alt.Bin(maxbins=20)
)
# No channel encoding options are specified in this chart
# so the code is the same as for the method-based syntax.