How do I resize my Plotly bar height and show only bar’s edge (in subplot)?

Viewed 2203

this is my first foray into Plotly. I love the ease of use compared to matplotlib and bokeh. However I'm stuck on some basic questions on how to beautify my plot. First, this is the code below (its fully functional, just copy and paste!):

import plotly.express as px
from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools

d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
       'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
           'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
            'Current': [15,9,20,10,20,8,10,21,18,14],
           'Goal': [50,35,21,44,20,24,14,29,28,19]
     }
dataset  = pd.DataFrame(d)

grouped = dataset.groupby('Category', as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']
fig1 = px.bar(dataset, x = v_current, y = v_cat, orientation = 'h',
              color_discrete_sequence = ["#ff0000"],height=10)
fig2 = px.bar(dataset, x = v_goal, y = v_cat, orientation = 'h',height=15)

trace1 = fig1['data'][0]
trace2 = fig2['data'][0]
fig = make_subplots(rows = 1, cols = 1, shared_xaxes=True, shared_yaxes=True)
fig.add_trace(trace2, 1, 1)
fig.add_trace(trace1, 1, 1)
fig.update_layout(barmode = 'overlay')
fig.show()

Here is the Output: enter image description here

Question1: how do I make the width of v_current (shown in red bar) smaller? As in, it should be smaller in height since this is a horizontal bar. I added the height as 10 for trace1 and 15 for trace2, but they are still showing at the same heights.

Question2: Is there a way to make the v_goal (shown in blue bar) only show it's right edge, instead of a filled out bar? Something like this: enter image description here

If you noticed, I also added a line under each of the category. Is there a quick way to add this as well? Not a deal breaker, just a bonus. Other things I'm trying to do is add animation, etc but that's for some other time!

Thanks in advance for answering!

2 Answers

Running plotly.express wil return a plotly.graph_objs._figure.Figure object. The same goes for plotly.graph_objects running go.Figure() together with, for example, go.Bar(). So after building a figure using plotly express, you can add lines or traces through references directly to the figure, like:

fig['data'][0].width = 0.4

Which is exactly what you need to set the width of your bars. And you can easily use this in combination with plotly express:

Code 1

fig = px.bar(grouped, y='Category', x = ['Current'],
             orientation = 'h', barmode='overlay', opacity = 1,
             color_discrete_sequence = px.colors.qualitative.Plotly[1:])
fig['data'][0].width = 0.4

Plot 1

enter image description here

In order to get the bars or shapes to indicate the goal levels, you can use the approach described by DerekO, or you can use:

for i, g in enumerate(grouped.Goal):
    fig.add_shape(type="rect",
                    x0=g+1, y0=grouped.Category[i], x1=g, y1=grouped.Category[i],
                    line=dict(color='#636EFA', width = 28))

Complete code:

import plotly.express as px
from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools

d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
       'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
           'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
            'Current': [15,9,20,10,20,8,10,21,18,14],
           'Goal': [50,35,21,44,20,24,14,29,28,19]
     }
dataset  = pd.DataFrame(d)

grouped = dataset.groupby('Category', as_index=False).sum()

fig = px.bar(grouped, y='Category', x = ['Current'],
             orientation = 'h', barmode='overlay', opacity = 1,
             color_discrete_sequence = px.colors.qualitative.Plotly[1:])

fig['data'][0].width = 0.4
fig['data'][0].marker.line.width = 0

for i, g in enumerate(grouped.Goal):
    fig.add_shape(type="rect",
                    x0=g+1, y0=grouped.Category[i], x1=g, y1=grouped.Category[i],
                    line=dict(color='#636EFA', width = 28))
f = fig.full_figure_for_development(warn=False)
fig.show()

You can use Plotly Express and then directly access the figure object as @vestland described, but personally I prefer to use graph_objects to make all of the changes in one place.

I'll also point out that since you are stacking bars in one chart, you don't need subplots. You can create a graph_object with fig = go.Figure() and add traces to get stacked bars, similar to what you already did.

For question 1, if you are using go.Bar(), you can pass a width parameter. However, this is in units of the position axis, and since your y-axis is categorical, width=1 will fill the entire category, so I have chosen width=0.25 for the red bar, and width=0.3 (slightly larger) for the blue bar since that seems like it was your intention.

For question 2, the only thing that comes to mind is a hack. Split the bars into two sections (one with height = original height - 1), and set its opacity to 0 so that it is transparent. Then place down bars of height 1 on top of the transparent bars.

If you don't want the traces to show up in the legend, you can set this individually for each bar by passing showlegend=False to fig.add_trace, or hide the legend entirely by passing showlegend=False to the fig.update_layout method.

import plotly.express as px
import plotly.graph_objects as go
# from plotly.subplots import make_subplots
import plotly as py
import pandas as pd
from plotly import tools

d = {'Mkt_cd': ['Mkt1','Mkt2','Mkt3','Mkt4','Mkt5','Mkt1','Mkt2','Mkt3','Mkt4','Mkt5'],
       'Category': ['Apple','Orange','Grape','Mango','Orange','Mango','Apple','Grape','Apple','Orange'],
           'CategoryKey': ['Mkt1Apple','Mkt2Orange','Mkt3Grape','Mkt4Mango','Mkt5Orange','Mkt1Mango','Mkt2Apple','Mkt3Grape','Mkt4Apple','Mkt5Orange'],
            'Current': [15,9,20,10,20,8,10,21,18,14],
           'Goal': [50,35,21,44,20,24,14,29,28,19]
     }
dataset  = pd.DataFrame(d)

grouped = dataset.groupby('Category', as_index=False).sum()
data = grouped.to_dict(orient='list')
v_cat = grouped['Category'].tolist()
v_current = grouped['Current']
v_goal = grouped['Goal']

fig = go.Figure()

## you have a categorical plot and the units for width are in position axis units
## therefore width = 1 will take up the entire allotted space
## a width value of less than 1 will be the fraction of the allotted space
fig.add_trace(go.Bar(
    x=v_current,
    y=v_cat,
    marker_color="#ff0000",
    orientation='h',
    width=0.25
    ))

## you can show the right edge of the bar by splitting it into two bars
## with the majority of the bar being transparent (opacity set to 0)
fig.add_trace(go.Bar(
    x=v_goal-1,
    y=v_cat,
    marker_color="#ffffff",
    opacity=0,
    orientation='h',
    width=0.30,
    ))

fig.add_trace(go.Bar(
    x=[1]*len(v_cat),
    y=v_cat,
    marker_color="#1f77b4",
    orientation='h',
    width=0.30,
    ))

fig.update_layout(barmode='relative')
fig.show()

enter image description here

Related