Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set non-zero zeroline in Plotly

I'm attempting to make a bar chart in Plotly using temperature, but want the zeroline to be centered around 32 when in Fahrenheit instead of at 0 (which is fine in Celsius mode). This way values below 32F have the bars go down instead of up.

An example of intended behavior is attached (which was done in HighCharts previously instead of Plotly)enter image description here

Neither y0, dy, or zeroline seem to allow this behavior.

like image 679
Alec Bennett Avatar asked Jan 19 '19 19:01

Alec Bennett


1 Answers

The parameter you are probably looking for has the intuitive name base.

base (number or categorical coordinate string)

Sets where the bar base is drawn (in position axis units). In "stack" or "relative" barmode, traces that set "base" will be excluded and drawn in "overlay" mode instead.

You can either use a list here or just a single value.

At least the bars are shifted now. Next we need to set zeroline of the yaxis to False to hide it and finally add our own zeroline via shapes.

import plotly
plotly.offline.init_notebook_mode()

val_celcius = [-50, 0, 50, 100]
val_fahrenheit = [c * 1.8 for c in val_celcius] # we don't need +32 here because of the shift by `base`

x = [i for i, _ in enumerate(val_celcius)]

data = plotly.graph_objs.Bar(x=[0, 1, 2, 3], 
                             y=val_fahrenheit,
                             text=['{}°C'.format(c) for c in val_celcius],
                             base=32)
layout = plotly.graph_objs.Layout(yaxis={'zeroline': False},
                                  shapes=[{'type': 'line', 
                                           'x0': 0, 'x1': 1, 'xref': 'paper',
                                           'y0': 32, 'y1': 32, 'yref': 'y'}])
fig = plotly.graph_objs.Figure(data=[data], layout=layout)
plotly.offline.iplot(fig)

enter image description here

like image 187
Maximilian Peters Avatar answered Jan 04 '23 00:01

Maximilian Peters