✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Horizontal xanchor barchart alignment

Hey guys,

I am wondering if it’s possible to change the x-axis alignment or anchor from right to left as opposed to left to right.
Currently I have a horizontal bar chart like this:


But I would like to have it in this orientation:

So far I figured out that adjusting layout.xaxis.range to [150,0] flips the bars and xaxis but not the labels or the colorbar.

Hi @Krulvis,

To change the starting position of the horizontal bars to the right, just reference your plot to xaxis and yaxis2 (yaxis2 is placed at the right side of the plot window), and set xaxis_autorange='reversed' (the latter also forces xaxis ticklabels to be displayed from right to left).

This setting: marker_colorbar_x =-0.15 places the colorbar at left.

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(specs=[[{"secondary_y": True}]])#secondary_y=True associates the right side yaxis
fig.add_trace(go.Bar(x= [4,2,7,5], y= ['A', 'B', 'C', 'D'], orientation='h',
                     marker_color=[3,2,1,5], marker_colorscale='matter', 
                     marker_colorbar_x=-0.15), secondary_y=True)
fig.update_xaxes(autorange='reversed')
fig.update_layout(width=600, height=400)

barplot-reversed

Capture

hi, could you show, how to get such a plot, or tell where to put the fig.update_xaxes(autorange=‘reversed’) if you have two subplots?

thanks

Hi @Garik,

You can define subplots of 1 rows and 2 columns, with the subplot (1, 2) referenced to the secondary yaxis and reversed xaxis2:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig=make_subplots(specs=[[{"secondary_y": False}, {"secondary_y": True}]],  
                  horizontal_spacing=0,
                  shared_yaxes=True,
                  rows=1, cols=2,print_grid=True )

x1 = [88.1, 88.8, 87.6, 88.5, 87.4]
text1 = [f'{t}%'  for t in x1]
y=['Men', 'Women','Shoes', 'Kids', 'Home']
fig.add_trace(go.Bar(orientation ='h',
                     x=x1,
                     y=y,
                     name='tr-name 1',
                     text=text1,
                     textposition='inside',
                     marker_color='#29428f'), 1, 1)
x2=[17212,8645,14164,8310, 15338]
fig.add_trace(go.Bar(orientation ='h',
                     x=x2,
                     y=y,
                     name='tr-name 2',
                     text=x2,
                     textposition='inside',
                     marker_color='#4169e1'), 1, 2, secondary_y=True)

fig.update_layout(width=550, height=500,
                  xaxis_showticklabels=False,
                  xaxis_title='%',
                  xaxis2_autorange='reversed',
                  xaxis2_title='Dist to Target',
                  yaxis3_showticklabels=False)

fig-two-bars

1 Like

thanks so much, it is very helpful.