如何在绘图条形图上左对齐文本(包含示例图像)[Plotly-Dash]

2022-01-21 00:00:00 python plotly plotly-dash

问题描述

我在向图表添加文本时需要帮助.

I need help in adding text to my graph.

我已经尝试过 text = 'y' 和 text-position = 'inside',但是对于小条形图,文本会垂直或被压扁,因此它可以放在条形图内.我只是想让它写出来.

I have tried text = 'y' and text-position = 'inside' but the text goes vertical or gets squashed for small bar charts so it can fit inside the bar. I just want it to write across.

这是需要修复的代码的工作示例:

Here is a working example of the code that needs fixing:

app = dash.Dash(__name__)
app.css.append_css({'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'})

    labels1 = ['0-7', '8-12', '13-15', '16-20', '21-25', '26+']
values1 = [10, 30, 10, 5, 6, 8]


labels2 = ['India', 'Scotland', 'Germany', 'NW England', 'N Ireland', 'Norway', 'NE England', 'Paris', 'North Africa', 'scandinavia']
values2 = [1, 0, 4, 9, 11, 18, 50, 7, 0, 2]

values3 = [10, 111, 75, 20]
labels4 = ['Safety Manager', 'Office Administrator', 'Internal Officer', 'Assistant Producer']

bar_color = ['#f6fbfc', '#eef7fa', '#e6f3f7', '#deeff5', '#d6ebf2', '#cde7f0', '#c5e3ed', '#bddfeb', '#b5dbe8', '#add8e6']
bar_color2 = ['#e6f3f7', '#deeff5', '#d6ebf2', '#cde7f0', '#c5e3ed', '#bddfeb', '#b5dbe8', '#add8e6']

app.layout = html.Div([
  html.Div([ 
    html.Div([
        dcc.Graph(id = 'age',
                          figure = {
                                    'data': [go.Bar(x = values1,
                                                    y = labels1,
                                                    orientation = 'h',
                                                    marker=dict(color = bar_color2),
                                                    text = labels1,
                                                    textposition = 'inside'
                                                    )
                                            ],
                                    'layout': go.Layout(title = 'Number of respondees per tenure',
                                                        yaxis=dict(
                                                                   zeroline=False,
                                                                   showline=False,
                                                                   showgrid = False,
                                                                   autorange="reversed",
                                                                   ),
                                                            xaxis=dict(
                                                                      zeroline=False,
                                                                      showline=False,
                                                                      showgrid = False
                                                                      )
                                                       )
                                  }
                         )
    ], className = 'four columns'),


    html.Div([
       dcc.Graph(id = 'location',
                                 figure = {
                                          'data': [go.Bar(x = values2,
                                                          y = labels2,
                                                          orientation = 'h',
                                                          marker=dict(color = bar_color),
                                                            text = labels2,
                                                            textposition = 'inside'
                                                         )
                                                  ],
                                          'layout': go.Layout(title = 'Number of respondees per region',
                                                                yaxis=dict(
                                                                          zeroline=False,
                                                                          showline=False,
                                                                          showgrid = False,
                                                                          autorange="reversed",
                                                                         ),
                                                                xaxis=dict(
                                                                          zeroline=False,
                                                                          showline=False,
                                                                          showgrid = False
                                                                         )                                                             ) 
                                        }
                                )
        ], className = 'four columns'),

    html.Div([
            dcc.Graph(id = 'job',
                                  figure = {
                                            'data': [go.Bar(x = values3,
                                                            y = labels4,
                                                            orientation = 'h',
                                                            marker=dict(color = bar_color2),
                                                            text = labels4,
                                                            textposition = 'inside'                                                            
                                                           )
                                                    ],
                                           'layout': go.Layout(title = 'Number of respondees per role',
                                                               yaxis=dict(
#                                                                         automargin=True,
                                                                          zeroline=False,
                                                                          showline=False,
                                                                          showgrid = False,
                                                                          autorange="reversed",
                                                                         ),
                                                                xaxis=dict(
                                                                          zeroline=False,
                                                                          showline=False,
                                                                          showgrid = False
                                                                         )
                                                              ) 
                                           }
                                )
        ], className = 'four columns')


  ], className = 'row')

])

if __name__ == '__main__':
app.run_server()

这是输出:

以下是我希望文本外观的示例:

Here's an example of how I want my text to look:

我在两件事上需要帮助:

I need help with two things:

  1. 使文本与栏的左侧而不是右侧对齐.
  2. 如果条形长度很短,我希望文本仍然可见(即使条形长度为零)并且不会被压扁或垂直对齐.

如果您还可以在第三张图表中解释如何修复 y 轴被切断,那就太棒了.现在,我必须更改标签以强制其适合,这很耗时.有没有办法为容器添加填充或其他东西?

If you can also give an explanation of how to fix y-axis being cut off in the third chart that would be amazing. For now, I have to change the labels to force it to fit which is time-consuming. Is there a way of adding padding to the container or something?

谢谢.


解决方案

这是一个不优雅的解决方法,但是在搜索了 plotly python 文档之后,我找不到任何可以用提供的 plotly 属性来满足你的要求.如果您现在需要一次性快速修复,请尝试使用 yaxis=dict(showticklabels=False) 并手动添加标签作为注释,例如:

This is an inelegant workaround, but after scouring the plotly python docs, I couldn't find anything that would do exactly what you were asking with the plotly attributes provided. If you need a one-time, quick fix now, try using yaxis=dict(showticklabels=False) and add your labels manually as annotations like:

layout = go.Layout(
    # Hide the y tick labels
        yaxis=dict(
        showticklabels=False),
    annotations=[
        dict(
        # I had to try different x values to get alignment
            x=0.8,
            y='giraffes',
            xref='x',
            yref='y',
            text='Giraffes',
            font=dict(
                family='Arial',
                size=24,
                color='rgba(255, 255, 255)'
            ),
            align='left',
        # Don't show any arrow
            showarrow=False,
        ), 

我得到的输出看起来像:

The output I got looked like:

您可以检查 Plotly Annotations 和 图表属性 文档看看有没有是什么更适合您的需求.

You can check the Plotly Annotations and Chart Attributes documentation to see if there is anything that better suits your needs.

我在将代码添加到问题之前就开始发布此回复.下面是一个示例,说明如何为相关代码中第一个图形的前两个 y 标签制作注释:

I started posting this response before the code was added to the question. Here is an example of how the annotations could be made for the first two y labels of the first graph in the code in question:

app.layout = html.Div([
  html.Div([ 
    html.Div([
        dcc.Graph(id = 'age',
                          figure = {
                                    'data': [go.Bar(x = values1,
                                                    y = labels1,
                                                    orientation = 'h',
                                                    marker=dict(color = bar_color2),
                                                    text = labels1,
                                                    textposition = 'inside'
                                                    )
                                            ],
                                    'layout': go.Layout(title = 'Number of respondees per tenure',
                                                        yaxis=dict(
                                                                   zeroline=False,
                                                                   showline=False,
                                                                   showgrid = False,
                                                                   showticklabels=False
                                                                   autorange="reversed",
                                                                   ),
                                                            xaxis=dict(
                                                                      zeroline=False,
                                                                      showline=False,
                                                                      showgrid = False
                                                                      )
                                                                   ),
                                                            annotations=[dict(
                                                                        x=0.8,
                                                                        y=labels1[0],
                                                                        xref='x',
                                                                        yref='y',
                                                                        text=labels1[0],
                                                                        font=dict(
                                                                            family='Arial',
                                                                            size=24,
                                                                            color='rgba(255, 255, 255)'
                                                                        ),
                                                                        align='left',
                                                                        showarrow=False,
                                                                    ), 
                                                                    dict(
                                                                        x=1.2,
                                                                        y=labels1[1],
                                                                        xref='x',
                                                                        yref='y',
                                                                        text=labels1[1],
                                                                        font=dict(
                                                                            family='Arial',
                                                                            size=24,
                                                                            color='rgba(255, 255, 255)'
                                                                        ),
                                                                        align='left',
                                                                        showarrow=False,
                                                                    ),

编辑 2: @ user8322222,要回答您评论中的问题,您可以使用列表理解来制作注释字典,如下所示:

Edit 2: @ user8322222, to answer the question in your comment, you could use a list comprehension to make your annotations dictionary like so:

 annotations1 = [dict(x=(len(labels1[i])*0.15), y=labels1[i], xref='x', yref='y', 
text=labels1[i], font=dict(family='Arial', size=24, color='rgba(255, 255, 255)'),
      align='left', showarrow=False) for i in range(len(labels1))]

但是我认为不会有一个常数可以乘以字符中的文本长度(就像我在示例中使用的 x 一样)以获得完美对齐.您可以对字符串使用像素长度或其他度量,如 这篇文章来设计一种更准确的方法来确定 x 以使其正确对齐.希望对您有所帮助.

However I don't think there will be a constant you could multiply by the length of the text in characters (like I used for x in the example) to get perfect alignment. You could use the pixel length or other measures for the string as in this post to devise a more accurate way of determining x to get it properly aligned. Hope that helps.

相关文章