Plotly Python 直方图:如何获取 y 尺度的值?

问题描述 投票:0回答:1

请对我手下留情。我对 Plotly 比较陌生 :-)

Currenlty,我正在绘制一个直方图,该直方图还用一条线标记了几个感兴趣的值。此外,我想提供一个图例,显示每个不同值的标签。因此,我正在使用以下功能:

def create_histogram(data: pd.DataFrame, property: str, inn_ids: list[str]) -> str:
    """
    Create a histogram for the given property amd marks all values of interest.

    Args:
        df (pd.DataFrame): _description_
        property (str): the property name which defines the histogram for plotting the histo.
        inn_ids (list[str]): the list defines all values which will be marked with a horizontal line in the plot.

    Returns:
        str: It returns the plot in json format.
    """

    for inn_id in inn_ids:
        if inn_id not in list(data["INN"]):
            raise ValueError(f"The INN ID {inn_id} does not exist in the data.")

    unit = ""

    fig = px.histogram(data, x=property)

    x_axis_description = load_property_description(property, "name")
    unit = load_property_description(property, "unit")

    if unit != property:
        x_axis_description = f"{x_axis_description} (in {unit})"

    fig.update_xaxes(title_text=x_axis_description)

    fig.update_yaxes(title_text="Count")

    for index, inn_id in enumerate(inn_ids):
        inn_value = data.loc[data["INN"] == inn_id, property].values[0]

        fig.add_trace(
            go.Scatter(
                x=[inn_value, inn_value],
                y=[0, max(data[property])],
                mode="lines",
                name=f"{inn_id} ({property}={inn_value})",
                line=dict(color=plot_line_colors[index], width=3.5, dash="dash"),
            )
        )

    fig.update_layout(showlegend=True)
    graph_json = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return graph_json

不幸的是,线

y=[0, max(data[property])],
画了一条很长的线,然后改变了整个直方图的y尺度。我正在为 python 使用 plotly。该图看起来像这样: enter image description here

有没有什么技巧可以解决这个问题,方法是找到没有直线的 w 直方图,y 标度上的 y 值最高,或者还有其他技巧吗?

随着调试器找到直方图的原始比例:-)

python plotly histogram
1个回答
0
投票

您可以找到图形的最大计数,然后使用该值设置 y 轴的范围。只需确保根据需要更改垃圾箱的数量,但从图像中看起来像 8 个。它看起来像这样:

import numpy as np

def create_histogram(data: pd.DataFrame, property: str, inn_ids: list[str]) -> str:
    """
    Create a histogram for the given property amd marks all values of interest.

    Args:
        df (pd.DataFrame): _description_
        property (str): the property name which defines the histogram for plotting the histo.
        inn_ids (list[str]): the list defines all values which will be marked with a horizontal line in the plot.

    Returns:
        str: It returns the plot in json format.
    """

    for inn_id in inn_ids:
        if inn_id not in list(data["INN"]):
            raise ValueError(f"The INN ID {inn_id} does not exist in the data.")

    unit = ""

    counts, edges = np.histogram(data[property], bins=8)  # adjust the number of bins as needed

    fig = px.histogram(data, x=property)

    x_axis_description = load_property_description(property, "name")
    unit = load_property_description(property, "unit")

    if unit != property:
        x_axis_description = f"{x_axis_description} (in {unit})"

    fig.update_xaxes(title_text=x_axis_description)

    fig.update_yaxes(title_text="Count", range=[0, max(counts)*1.2])  # adjust the range multiplier as needed

    for index, inn_id in enumerate(inn_ids):
        inn_value = data.loc[data["INN"] == inn_id, property].values[0]

        fig.add_trace(
            go.Scatter(
                x=[inn_value, inn_value],
                y=[0, max(counts)*1.2],
                mode="lines",
                name=f"{inn_id} ({property}={inn_value})",
                line=dict(color=plot_line_colors[index], width=3.5, dash="dash"),
            )
        )

    fig.update_layout(showlegend=True)
    graph_json = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return graph_json

© www.soinside.com 2019 - 2024. All rights reserved.