最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Adjust the bars in the chart based on the subset condition - Stack Overflow

programmeradmin4浏览0评论

I am facing an issue as shown in the image below, I am trying to generate the bar chart based on the treatments as a group, based on the drop-down, if I unselect a treatment the bar should disappear and show the bars of the remaining treatments, however when I unselect a treatment, there are gaps created. how to avoid them, please help.

def plot_(data,selected_trt):
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    import streamlit as st

    # Create the bar chart
    plt.figure(figsize=(10, 7))
    # plt.barh(data['USUBJID_numeric'], data['max_ady'], color='skyblue', edgecolor='black', alpha=0.8)
    

    data = data[data['TRT01P'].isin(selected_trt)]

    # Example dataset (replace with your data's column of treatment groups)
    unique_treatments = data['TRT01P'].unique()

    # Define a set of colors (expand or change as needed)
    color_palette = plt.cm.Pastel1.colors  # Use a colormap (e.g., Pastel1, Set2, etc.)
    num_colors = len(color_palette)

# Generate the treatment_colors dictionary dynamically
    treatment_colors = {
    treatment: color_palette[i % num_colors]  # Cycle through the color palette if treatments exceed colors
    for i, treatment in enumerate(unique_treatments)
    }



    
    # Assign colors based on the treatment group
    data['color'] = data['TRT01P'].map(treatment_colors)
    xupper = data['max_ady'].max()

    # Create the bar chart
    plt.figure(figsize=(10, 7))

    # for _, row in data.iterrows():
    for _, row in data.iterrows():
        plt.barh(
            row['USUBJID_numeric'],  # Subject on the y-axis
            row['max_ady'],          # Days of treatment on the x-axis
            color=row['color'],      # Color based on treatment group
            edgecolor='black',
            alpha=0.8
        )

    legend_elements = [
        Line2D([0], [0], color=color, lw=4, label=treatment)
        for treatment, color in treatment_colors.items()
    ]
    plt.legend(handles=legend_elements, title='Treatments', loc='best')
    # Update the y-axis ticks to show original USUBJID values
    plt.yticks(data['USUBJID_numeric'], data['USUBJID'])

    # Add labels and title
    plt.xlabel('Days of Treatment')
    plt.ylabel('Subjects')
    # plt.title('Swimmer Plot for Treatment Exposure')
    # Adjust axis limits to start at (0, 0)
    plt.margins(x=0, y=0.01)
    ax = plt.gca()
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    plt.xlim(0, xupper+100) 

    # Display the plot in Streamlit
    st.pyplot(plt.gcf())

I am facing an issue as shown in the image below, I am trying to generate the bar chart based on the treatments as a group, based on the drop-down, if I unselect a treatment the bar should disappear and show the bars of the remaining treatments, however when I unselect a treatment, there are gaps created. how to avoid them, please help.

def plot_(data,selected_trt):
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    import streamlit as st

    # Create the bar chart
    plt.figure(figsize=(10, 7))
    # plt.barh(data['USUBJID_numeric'], data['max_ady'], color='skyblue', edgecolor='black', alpha=0.8)
    

    data = data[data['TRT01P'].isin(selected_trt)]

    # Example dataset (replace with your data's column of treatment groups)
    unique_treatments = data['TRT01P'].unique()

    # Define a set of colors (expand or change as needed)
    color_palette = plt.cm.Pastel1.colors  # Use a colormap (e.g., Pastel1, Set2, etc.)
    num_colors = len(color_palette)

# Generate the treatment_colors dictionary dynamically
    treatment_colors = {
    treatment: color_palette[i % num_colors]  # Cycle through the color palette if treatments exceed colors
    for i, treatment in enumerate(unique_treatments)
    }



    
    # Assign colors based on the treatment group
    data['color'] = data['TRT01P'].map(treatment_colors)
    xupper = data['max_ady'].max()

    # Create the bar chart
    plt.figure(figsize=(10, 7))

    # for _, row in data.iterrows():
    for _, row in data.iterrows():
        plt.barh(
            row['USUBJID_numeric'],  # Subject on the y-axis
            row['max_ady'],          # Days of treatment on the x-axis
            color=row['color'],      # Color based on treatment group
            edgecolor='black',
            alpha=0.8
        )

    legend_elements = [
        Line2D([0], [0], color=color, lw=4, label=treatment)
        for treatment, color in treatment_colors.items()
    ]
    plt.legend(handles=legend_elements, title='Treatments', loc='best')
    # Update the y-axis ticks to show original USUBJID values
    plt.yticks(data['USUBJID_numeric'], data['USUBJID'])

    # Add labels and title
    plt.xlabel('Days of Treatment')
    plt.ylabel('Subjects')
    # plt.title('Swimmer Plot for Treatment Exposure')
    # Adjust axis limits to start at (0, 0)
    plt.margins(x=0, y=0.01)
    ax = plt.gca()
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    plt.xlim(0, xupper+100) 

    # Display the plot in Streamlit
    st.pyplot(plt.gcf())
Share Improve this question edited Jan 24 at 8:07 Vikas Sharma 2,1411 gold badge13 silver badges25 bronze badges asked Jan 20 at 17:44 jkatamjkatam 3,4471 gold badge6 silver badges12 bronze badges 2
  • I see that someone has down voted this question without any reason. If at least a reason is given then I can correct it. This is something I want stackoverflow to check, here every question is important, yes the way we ask might differ but that can always be corrected. Already, now due to Chat GPT the number of people visiting stackoverflow has decreased and some people like me who are visiting are discouraged like this, then it will still decrease the number of people visiting here or posting questions here. – jkatam Commented Jan 21 at 4:02
  • Please provide a bit more info in your answer and accept it if it resolves the issue you are facing. Thanks! – Vikas Sharma Commented Jan 24 at 8:08
Add a comment  | 

1 Answer 1

Reset to default 0

The issue is resolved when i re-derived the USUBJID_numeric after the subset

data['USUBJID_numeric'] = pd.Categorical(data['USUBJID']).codes
发布评论

评论列表(0)

  1. 暂无评论