Python Plotly 条形图 - 如何在图表上添加水平线?

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

我有一个显示的条形图;

生成此代码的代码如下;

def create_bar_chart(_dict, _title, _title_text, titles, image_paths):
    _fig = go.Figure()
    df = pd.DataFrame(dict(score=_dict.values(), trait=_dict.keys()))
    _image = f"{_title_text}_sm.jpg"
    _width=600
    _height=400

    _fig = px.bar(df, x="trait", y="score")
    _fig.update_layout(xaxis_title=None)

我想为每个条形图放置一条水平线(宽度与条形图相同)来指示平均值。该值可能高于条形图或条形图内。例如,对于分析思维,平均值可能是 0.2 或 0.4,所以我需要一条带有该分数的水平线。我该怎么做?

python-3.x plotly
1个回答
0
投票

下面是我对问题中需求的解释,其中在某个平均分数的高度绘制了一条与每个条形相同宽度的水平线

import plotly.graph_objects as go
import pandas as pd
import numpy as np


data_dict = {
    'trait': ['analytical thinking', 'cognitive processes', 'certainty', 'insight', 'abstract', 'concrete'],
    'score': [0.35, 0.15, 0.02, 0.05, 0.42, 0.2]
}

X_COUNT = len(data_dict['trait'])
# The x-axis of bar chart is divided evenly by the number of x elements. This width is
# not necessarily the bar width, but the entire width for x element, which includes the
# bar and the two gaps on either side.
TOTAL_WIDTH = 1 / X_COUNT
# Set the gap between bars. It is a percentage of TOTAL_WIDTH. In other words, if we
# have TOTAL_WIDTH = 1 and BAR_GAP = 0.2, then the bar width would be 0.8 and the gaps
# between two bars would be 0.2
BAR_GAP = 0.3

fig = go.Figure()
fig = px.bar(df, x='trait', y='score')
fig.update_layout(
    width=600,
    height=400,
    bargap=BAR_GAP,
)

# The relative starting position of each bar (i.e., considering the width of the chart
# as 1)
bar_starts = np.cumsum([TOTAL_WIDTH] * X_COUNT) - 1 / X_COUNT

averages = [0.2, 0.3, 0.1, 0.02, 0.35, 0.25]  # whatever average score to plot
for bs, ave in zip(bar_starts, averages):
    line_st = bs + TOTAL_WIDTH * BAR_GAP / 2
    fig.add_shape(
        type='line',
        x0=line_st,
        y0=ave,
        x1=line_st + TOTAL_WIDTH * (1 - BAR_GAP),
        y1=ave,
        xref='paper',  # relative x position
        yref='y'  # exact y position as shown on the y-axis
    )
fig.show()

剧情是这样的

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