简体   繁体   English

带有下拉菜单的 Altair 条形图 - 选择和不选择时保持条形宽度相同

[英]Altair bar chart with dropdown- keeping bar width same both with selection and without

I am trying to create a chart in Altair with dropdowns.我正在尝试在 Altair 中创建一个带有下拉菜单的图表。 Here's the code这是代码

df = pd.DataFrame([["Merc","US",500, "Car_A"], ["BMW","US" ,55, "Car_B"]
                   , ["BMW","US",40, "Car_C"], ["Merc", "China",650, "Car_D"]
                  , ["BMW","US",80, "Car_E"], ["Merc", "China",850, "Car_F"]], columns=list("ABCD"))

position_dropdown_Type = alt.binding_select(name = "Type:" , options=[None] + list(df["B"].unique()), labels = ['All'] + list(df["B"].unique()))
position_selection_Type = alt.selection_single(fields=['B'], bind=position_dropdown_Type)

position_dropdown_1_Car = alt.binding_select(name = "Company:", options=[None] + list(df["A"].unique()), labels = ['All'] + list(df["A"].unique()))
position_selection_1_Car = alt.selection_single(fields=['A'], bind=position_dropdown_1_Car, name = "__")

#interval = alt.selection_multi(fields=['GICS_SUB_IND'], bind='legend')
Car_bar=alt.Chart(df).mark_bar().encode(
            color = 'A',   
            y = alt.Y('C', scale=alt.Scale(domain=[0, 1.2*df["C"].max()]),
                      title = 'Range'),
            x = alt.X('D:O', sort = alt.EncodingSortField(field="C", order='ascending', op='max'), title = 'Care_Name')
             ).add_selection(interval).add_selection(position_selection_Type).transform_filter(position_selection_Type).add_selection(position_selection_1_Car).transform_filter(position_selection_1_Car)

(Car_bar).properties(width = 700)

the code works with a graph like this when all values are selected the code works with a graph like this when all values are selected 在此处输入图像描述

However, when I make a selection, the bar width takes the entire width as seen below但是,当我进行选择时,条形宽度会占据整个宽度,如下所示在此处输入图像描述

Defining size inside mark_bar(size = 10) is not an option as the code will be accessing different datasets with wide range of sample size.mark_bar(size = 10)中定义大小不是一个选项,因为代码将访问具有广泛样本大小的不同数据集。 Also, since the dropdown list will be quite long, selecting from the legend is also not ideal.此外,由于下拉列表会很长,因此从图例中进行选择也不理想。

Is there a way to keep the width same for the bars with the selection from dropdown?有没有办法通过下拉选择保持条的宽度相同?

It seem the issue is with the properties(width = 700) setting.似乎问题出在properties(width = 700)设置上。 It is forcing the bar width to be large enough to satisfy the width setting.它迫使条形宽度足够大以满足宽度设置。 If you remove that, it will give adapt the bar width accordingly.如果您删除它,它将相应地调整条形宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM