Skip to content Skip to sidebar Skip to footer

Plotly-python: How To Make A Gapped Y Axis?

Courtesy to the original question for Plotly-R. The following will focus on Python. Is it possible to create a plotly bar chart, e.g. any chart from the following website: plotly.

Solution 1:

To my knowledge, plotly hasn't got any built-in functionality to do this. But it's still possible to make a figure that matches your image using subplots if you:

  1. use make_subplots(rows=2, cols=1, vertical_spacing = <low>),
  2. add the same traces to figure positions [1, 1] and [2, 1],
  3. remove x-axis labels for [1, 1], and
  4. adjust the y axes for figure positions [1, 1] and [2, 1] to respectively start and end with your desired cutoff values in a defined interval.

Plot:

enter image description here

Complete code:

# importsimportplotly.graph_objectsasgoimportplotly.expressaspximportpandasaspdfromplotly.subplotsimportmake_subplots# datadf=pd.DataFrame({'years': [1995, 1996, 1997, 1998, 1999, 2000,
                             2001, 2002, 2003, 2004, 2005, 2006,
                             2007, 2008, 2009, 2010, 2011, 2012],'China': [219, 146, 112, 127, 124, 180, 236,
                            207, 236, 263,350, 430, 474, 1526,
                            488, 537, 500, 439],'Rest of world': [16, 13, 10, 11, 28, 37,
                                        43, 55, 56, 88, 105, 156, 270,
                                        299, 340, 403, 549, 1499]})df.set_index('years',inplace=True)# colors and cut-offscolors=px.colors.qualitative.Plotlycut_interval= [600, 1400]

# subplot setupfig=make_subplots(rows=2,cols=1,vertical_spacing=0.04)fig.update_layout(title="USA plastic scrap exports (...with some made-up values)")# Traces for [2, 1]# marker_color=colors[i] ensures that categories follow the same color cyclefori,colinenumerate(df.columns):fig.add_trace(go.Bar(x=df.index,y=df[col],name=col,marker_color=colors[i],legendgroup=col,),row=2,col=1)# Traces for [1, 1]# Notice that showlegend = False.# Since legendgroup = col the interactivity is# taken care of in the previous for-loop.fori,colinenumerate(df.columns):fig.add_trace(go.Bar(x=df.index,y=df[col],name=col,marker_color=colors[i],legendgroup=col,showlegend=False,),row=1,col=1)# Some aesthetical adjustments to layoutfig.update_yaxes(range=[cut_interval[1],max(df.max()*1.1)],row=1,col=1)fig.update_xaxes(visible=False,row=1,col=1)fig.update_yaxes(range=[0,cut_interval[0]],row=2,col=1)fig.show()

Post a Comment for "Plotly-python: How To Make A Gapped Y Axis?"