散点图和带区间选择的直方图#
这个例子展示了如何将散点图和直方图链接在一起,使得在直方图中的区间选择将会在散点图中绘制所选的值。
请注意,两个子图都需要知道由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.