Black Lives Matter. Please consider donating to Black Girls Code today.

Specify title position

Hi all,

I’m quite new to using plotly, and I want to reduce the amount of whitespace between my title and the actual plot itself. I can’t seem to find any way to do it. Is there a way to adjust this?

Thanks,

Harry T

trace1 = py.graph_objs.Bar(
x = df_station_counts[‘stype_code’],
y = df_station_counts[‘diversion_percentage’],

marker = dict(
    color = 'blue',
    ),
hoverinfo = 'y',
opacity = 0.8

)

data = [trace1]

layout = py.graph_objs.Layout(
barmode = ‘group’,
autosize = False,
width = 2000,
height = 1000,
margin = dict(b = 100,),
title = ’ diversion fraction by station’,
titlefont = dict(size = 40),
xaxis=dict(
title = ’
station’,
titlefont = dict(
size = 30),
tickfont=dict(
size=20,

    ),
        tickangle = 90,
        
    ),
    yaxis=dict(
        title  = 'diversion percentage / %',
        titlefont = dict(
            size = 30),
        tickfont=dict(
            size=20,
        
    ),
        hoverformat = '.2f',

    ),

)

fig = py.graph_objs.Figure(data=data, layout=layout)
py.offline.iplot(fig)

Have you tried lowering the top margin value (in margin.t)?

hi @etienne

I tried doing this however it didnt seemt to change the distance between the title and the plot, it just changed the amount of whitespace above the title. I was able to get around the problem by adding in a line break at the start of the title.

Thanks,

Harry

How to position the title directly above the chart (independently of margin):

fig.update_layout(
  title={
    "yref": "paper",
    "y" : 1,
    "yanchor" : "bottom"   
  }
)

(Or specify the same thing in go.Layout)

How does it work?

  • yref is used to position the title relative to the actual chart ("paper") and not the container (which would be "container")
  • y is a value between 0 and 1 which sets the relative position. Setting it to 1 will put the title at the top of the chart; setting it to 0 will put the title at the bottom of the chart etc.
  • yanchor sets what part of the title will touch its y location. Without this property the title would now be at the top, but inside the chart (i.e. aligned with the "top"). We set "bottom" so that the bottom of the title will be aligned with the top of the chart, i.e. the title will be located precisely above the chart.

For adding a little padding between the title and the chart use the pad property of the title (look it up in the reference). For vertically positioning the title (e.g. centering it) you can use xref, x and xanchor in the same way.