我想用牵牛星做一个互动图,可以用一个简单的例子来描述:假设我有四栋房子a,B,C,D,在一个2x2的网格中。对于每一对房子,都有一个相关的友谊分数来表示双方的友谊。一个很好的可视化方法是绘制房屋的2x2网格,当我点击其中一块瓷砖时,友谊分数会显示在所有其他瓷砖上,并带有颜色编码
我有一个解决方案,只有在点击其中一个瓷砖时才有效。选择其他三个平铺时不受影响。在下面的例子中,我还绘制了下面的友谊得分矩阵(为了清晰起见),这里基于选择的颜色似乎确实有效
import altair as alt
import pandas as pd
families = ["A", "B", "C", "D"]
# geographical house locations
df = pd.DataFrame(
{
"x": [1, 2, 1, 2],
"y": [1, 1, 2, 2],
"house1": families,
}
)
# friendship data
firendship_df = pd.DataFrame(
[[0, 1, 2, 3], [1, 0, 2, 3], [2, 2, 0, 1], [3, 3, 1, 0]], columns=families
)
firendship_df = firendship_df.set_index(firendship_df.columns)
# convert friendship matrix to long format
friendship_df_lf = (
firendship_df.melt(var_name="house1", value_name="friendship", ignore_index=False)
.reset_index()
.rename(columns={"index": "house2"})
)
df = pd.merge(df, friendship_df_lf, how="left", on="house1")
selector = alt.selection_single(name="SelectorName", fields=["house1"])
base = (
alt.Chart(df, width=200, height=200)
.mark_rect(strokeWidth=1, stroke="white")
.encode(
x=alt.X("x:N"),
y=alt.Y("y:N"),
)
)
geo_chart = (
base.mark_rect(strokeWidth=1, stroke="white")
.add_selection(selector)
.transform_calculate(selected_val=selector["house1"])
.encode(
color=alt.condition(
"datum.selected_val==datum.house2",
alt.Color(
"friendship:O",
scale=alt.Scale(scheme="redyellowblue", domain=[0, 1, 2, 3]),
),
alt.value("grey"),
),
)
)
score_chart = (
alt.Chart(friendship_df_lf, width=200, height=200)
.mark_rect()
.encode(
x="house1:N",
y="house2:N",
color=alt.condition(
selector,
alt.Color(
"friendship:O",
scale=alt.Scale(scheme="redyellowblue", domain=[0, 1, 2, 3]),
),
alt.value("grey"),
),
)
)
# add house labels to plot
text_chart = base.mark_text().encode(text="house1")
tot_chart = geo_chart + text_chart
alt.vconcat(tot_chart, score_chart).show()
单击“房屋D”时按预期工作的绘图:
单击其他房屋时显示问题的绘图。这里是A座房子:
如果我理解正确,您希望在
geo_chart
中单击的互动程序和score_chart
中相应的列在您单击geo_chart
时高亮显示。要实现这一点,您可以将geo_chart
的颜色条件从"datum.selected_val==datum.house2"
更改为与其他图表相同的selector
相关问题 更多 >
编程相关推荐