我试图在Altair中创建两层柱状图(每个柱状图有一个垂直的平均标尺)。我想要一个图例来标记这四个
我正在使用可以找到的第一个“出生体重I”数据here
我的代码(很长,抱歉)如下所示:
from altair import datum
# This histogram for baby weights of mothers who dont smoke
dont = alt.Chart(babyData).mark_bar().encode(
alt.X("bwt-oz:Q", axis=alt.Axis(title='Birth Weight (Ounces)'), bin=True),
alt.Y('count()', axis=alt.Axis(title='Count'), scale=alt.Scale(domain=[0, 350]))
).properties(
width=400,
height=400
).transform_filter(
datum.smoke == 0,
)
mean = alt.Chart(babyData).mark_rule(color='red').encode(
x='mean(bwt-oz):Q',
size=alt.value(4)
).transform_filter(
datum.smoke == 0
)
dontSmokeChart = dont + mean
# This histogram for baby weights of mothers who smoke
do = alt.Chart(babyData).mark_bar().encode(
alt.X("bwt-oz:Q", axis=alt.Axis(title='Birth Weight (Ounces)'), bin=True),
alt.Y('count()', axis=alt.Axis(title='Count'), scale=alt.Scale(domain=[0, 350]))
).transform_filter(
datum.smoke == 1
).properties(
width=400,
height=400
)
mean2 = alt.Chart(babyData).mark_rule(color='red').encode(
x='mean(bwt-oz):Q',
size=alt.value(4)
).transform_filter(
datum.smoke == 1
)
doSmokeChart = do + mean2
# This layers, and puts them all together
layer = alt.layer(
dont,
mean,
do,
mean2
).properties(
title="Layered Histogram of Baby Weights of Mothers Who smoke Vs. Who Don't",
).configure_mark(
opacity=0.5,
color='blue',
)
layer
我只想要一个图例,说明哪个直方图/平均值属于哪个直方图/平均值。
如果我也能给它们涂上颜色,或许可以用这种方式添加一个传奇,那也不错,但我不知道怎么做
谢谢你的洞察力
@jakevdp刚刚击败了我!我也要说同样的话。这里有一个完整的示例供您使用
您不应使用过滤数据手动创建图层,而应在完整数据集上使用颜色编码:然后将自动生成图例
例如:
从那里,您可以使用标准方法来处理每个标记使用的Customize the color schemes
相关问题 更多 >
编程相关推荐