简体   繁体   English

如何在堆叠的水平条形图中将跟踪文本对齐到中心

[英]How to align trace text to center in a stacked horizontal bar chart

I have a stacked horizontal bar and I want text defined for each trace to be placed at the center of the corresponding bar.我有一个堆叠的水平条,我希望为每个跟踪定义的文本放置在相应条的中心。 I can't find an attribute that sets this without using anotations, but I'd like to use "text" for each trace and just be able to align it.我找不到在不使用注释的情况下设置它的属性,但我想为每个跟踪使用“文本”并且能够对齐它。

I'm using Plotly 3.4.1 with Jupyter (Plotly offline).我正在使用带有 Jupyter 的 Plotly 3.4.1(Plotly 离线)。 Couldn't find any documentation about how to do this except trying to do this with annotations, which look like a more suitable solution if I want to pinpoint an explicit coordinate.除了尝试使用注释执行此操作外,找不到任何有关如何执行此操作的文档,如果我想确定显式坐标,这看起来是更合适的解决方案。 What I want is a much simpler (something like "align": "center"), but couldn't find any attribute for this under go.Bar我想要的是一个更简单的(类似于“align”:“center”),但在 go.Bar 下找不到任何属性

Just want the "80", "20" to appear at the center instead of aligned to the right只希望“80”、“20”出现在中心而不是向右对齐

from plotly.offline import iplot, plot, init_notebook_mode
import plotly.graph_objs as go

def getStackedSentimentHbar():
    trace0 = go.Bar(
        y=["A","B"],
        x=[20,80],
        orientation = 'h',
        text=["20","80"],
        textposition="inside",
        hoverinfo = "none",
    )
    trace1 = go.Bar(
        y=["A","B"],
        x=[80,20],
        orientation = 'h',
        text=["80","20"],
        textposition="inside",
        hoverinfo = "none",
    )
    data = [trace0,trace1]
    layout = go.Layout(
        barmode='stack',
        showlegend=False,
        xaxis=dict(
            showgrid=False,
            zeroline=False,
            showline=False,
            ticks='',
            showticklabels=False
        ),
        yaxis=dict(
            showgrid=False,
            zeroline=False,
            showline=False,
            ticks='',
            showticklabels=True
        ),
        margin = dict(
            l = 200, 
            r = 50, 
            b = 50, 
            t = 50, 
            pad = 10
        ),
        font=dict(
            family='Heebo', 
            size=18, 
            color='#000000'
        )
    )
    fig = go.Figure(data=data, layout=layout)
    return fig

init_notebook_mode()
fig = getStackedSentimentHbar()
iplot(fig)

As far as I know there is no such parameter in Plotly but we can always hack to Plotly :)据我所知,Plotly 中没有这样的参数,但我们总是可以破解 Plotly :)

Let's just duplicate all x- and y-values but leave the text as it is.让我们复制所有 x 和 y 值,但保留text原样。

In the code below there are two functions, getStackedSentimentHbar and getStackedSentimentHbarCentered .在下面的代码中有两个函数, getStackedSentimentHbargetStackedSentimentHbarCentered The first one returns the original graph, the second returns the graph with the (almost) centered labels.第一个返回原始图,第二个返回带有(几乎)居中标签的图。

在此处输入图片说明

from plotly.offline import iplot, plot, init_notebook_mode
import plotly.graph_objs as go

LAYOUT = go.Layout(
        barmode='stack',
        showlegend=False,
        xaxis=dict(
            showgrid=False,
            zeroline=False,
            showline=False,
            ticks='',
            showticklabels=False
        ),
        yaxis=dict(
            showgrid=False,
            zeroline=False,
            showline=False,
            ticks='',
            showticklabels=True
        ),
        margin = dict(
            l = 200, 
            r = 50, 
            b = 50, 
            t = 50, 
            pad = 10
        ),
        font=dict(
            family='Heebo', 
            size=18, 
            color='#000000'
        )
    )

def getStackedSentimentHbar(values):

    data = []
    for i, x in enumerate(values['x']):
        trace = go.Bar(
            x=x,
            y=values['y'][i],
            orientation='h',
            text=x,
            textposition='inside',
            hoverinfo = 'none',
        )
        data.append(trace)

    fig = go.Figure(data=data, layout=LAYOUT)
    return fig

def getStackedSentimentHbarCentered(values):

    data = []
    for i, x in enumerate(values['x']):

        trace = go.Bar(
            x=[int(i / 2) for i in x * 2],
            y=values['y'][i] * 2,
            orientation = 'h',
            text=x,
            textposition='inside',
            hoverinfo = 'none'
        )
        data.append(trace)

    fig = go.Figure(data=data, layout=LAYOUT)
    return fig

values = {'x': [[20, 80], [80, 20]],
          'y': [['A', 'B'], ['A', 'B']]}

init_notebook_mode()
fig = getStackedSentimentHbarCentered(values)
iplot(fig)

A better approach - use separate annotations.更好的方法 - 使用单独的注释。

在此处输入图片说明

 var x1A = 20; var x1B = 80; var x2A = 80; var x2B = 20; var trace1 = { y: ['A', 'B'], x: [x1A, x1B], type: 'bar', orientation: 'h', }; var trace2 = { y: ['A', 'B'], x: [x2A, x2B], type: 'bar', orientation: 'h', }; var data = [trace1, trace2]; var layout = { barmode: 'stack', annotations: [ { x: x1A / 2, y: 'A', text: '20', showarrow: false }, { x: x1A + x2A / 2, y: 'A', text: '80', showarrow: false }, { x: x1B / 2, y: 'B', text: '80', showarrow: false }, { x: x1B + x2B / 2, y: 'B', text: '20', showarrow: false }, ], }; Plotly.newPlot('myDiv', data, layout);
 <head> <!-- Load plotly.js into the DOM --> <script src='https://cdn.plot.ly/plotly-2.0.0.min.js'></script> </head> <body> <div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div> </body>

Here is an example from the official Plotly documentation: https://plotly.com/python/horizontal-bar-charts/#color-palette-for-bar-chart这是官方 Plotly 文档中的一个示例: https ://plotly.com/python/horizo​​ntal-bar-charts/#color-palette-for-bar-chart

正如对此问题的回答所述,您可以通过设置insidetextanchor="start" (或“中间”或“结束”)更轻松地完成此操作

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

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