pandas 在plotly python facet组条形图中删除未使用类别中的间隙

vbkedwbf  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(73)

是否有简单的方法来消除属于一个组的酒吧之间的差距?为了说明这一点,在我的例子中,示例数据中的“动作”永远不会在分面变量“动物”上重叠,因此这些值对于“其他”“动物”总是缺失的。
编辑:如评论中所问,子图内的间隙是期望的(例如通常使用类别,仅缺少一个示例),以保持每个子图的一致布局。只保留空间的类别专门属于另一个子情节应删除。

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

data = [
    [1, 10, "dog", "run"], 
    [2, 15, "dog", "run"],
    [2, 13, "fish", "dive"],
    [1, 14, "fish", "swim"],
    [2, 13, "dog", "bark"],
    [1, 12, "dog", "growl"],
    [2, 12, "dog", "growl"],
    [1, 16, "fish", "dive"],
    [2, 7, "fish", "blub"],
    [1, 7, "fish", "swim"]
]
df = pd.DataFrame(data, columns=['day', 'temperature', "animal", "action"])

fig = px.bar(
        df,
        x=df["temperature"],
        y=df["day"].astype(str), # to use only existing values, 
        color="action",
        barmode="group",
        orientation="h",
        facet_row="animal",
        height=600
    )
fig.show()

qyyhg6bp

qyyhg6bp1#

我试过很多方法。我最接近的方法就是把栅栏分开。我知道这不完全是你想要的,但至少是接近的。

data = [
    [1, 10, "dog", "run"], 
    [2, 15, "dog", "run"],
    [2, 13, "fish", "dive"],
    [1, 14, "fish", "swim"],
    [2, 13, "dog", "bark"],
    
    [1, 12, "dog", "growl"],
    [2, 12, "dog", "growl"],
    [1, 16, "fish", "dive"],
    [2, 7, "fish", "blub"],
    [1, 7, "fish", "swim"]
]
df = pd.DataFrame(data, columns=['day', 'temperature', "animal", "action"])

# take all unique animals
animals = df['animal'].unique()
print(animals) # prints ['dog', 'fish']

# for each animal in list, create the plot and print it
for a in animals:
    df_temp=df.loc[df['animal'] == a]
    fig = px.bar(
            df_temp,
            x=df_temp["temperature"],
            y=df_temp["day"].astype(str), # to use only existing values, 
            color="action",
            barmode="group",
            orientation="h",
            facet_row="animal",
            height=300
        )
    
    fig.show()

请让我知道这个解决方案是否让你满意。

相关问题