How to make Dashboard Widgets using Python?-Part 2

Deepak Radhakrishnan
()
How to make Dashboard Widgets using Python?-Part 2

I present to you the second part on how to make dashboard widgets using python. This time I am going to elaborate on how we make use of bar charts for that matter. So let us dive right in.

Bar Chart

Charts are one of the most popular and effective ways for you to represent correlations of data. Among the charts, the Bar Charts are on the top of the list because instead of looking at a table of numerical data they allow the reader to identify patterns or trends easier way. It is also used for comparing and contrasting frequencies, numbers as well as other measures of various categories of data.

Contents

Overview

Bar Charts aids every dashboard for data visualization and also for a quick comparison between the two groups. To get a deeper understanding, let us practice some examples to generate Bar Charts.

If Dash is not installed in your system or if you have missed out on the first part of this tutorial, you should go check out the Installation part over here.

Plotting a simple Bar Charts

import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Energy Usage'),

    html.Div(children='''
        Energy Usage Chart.
    '''),

    dcc.Graph(
        id='new-graph',
        figure={
            'data': [
                {'x': ['Jan','Feb','Mar','Apr'], 'y': [231,375,765,800], 'type': 'bar', 'name': 'Year 2020'},
           
            ],
            'layout': {
                'title': 'Energy Usage Analysis '
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Making Bar Charts is simple just like the line chart. All you have to do is to change ” type=’bar’ “.

Output

Plotting Grouped Bar Charts

import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Energy Usage'),

    html.Div(children='''
        Energy Usage chart.
    '''),

    dcc.Graph(
        id='new-graph',
        figure={
            'data': [
                {'x': ['Jan','Feb','Mar','Apr'], 'y': [231,375,765,800], 'type': 'bar', 'name': 'Year 2020'},
{'x': ['Jan','Feb','Mar','Apr'], 'y': [531,675,165,987], 'type': 'bar', 'name': 'Year 2019'},
{'x': ['Jan','Feb','Mar','Apr'], 'y': [453,234,545,567], 'type': 'bar', 'name': 'Year 2018'},
{'x': ['Jan','Feb','Mar','Apr'], 'y': [743,657,678,508], 'type': 'bar', 'name': 'Year 2017'},

           
            ],
            'layout': {
                'title': 'Energy Usage Analysis '
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

It’s child’s play to add multiple data sets to a group and to make Bar Charts. Also, you could make mixed Charts by changing the type.

Output

Stacked Bar Charts

In some use cases, where you want to know the total, ie, produced by the groups – the stacked charts play a crucial role. You can stack the bar groups together and see the total.

import plotly.express as px
import plotly.graph_objects as go # or plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

data = px.data.gapminder()
boards=['Arduino', 'Raspberry Pi', 'BeagleBone']

fig = go.Figure(data=[
    go.Bar(name='Sector 1', x=boards, y=[20, 14, 23]),
    go.Bar(name='Sector 2', x=boards, y=[12, 18, 29])
])

fig.layout={
                'title': '',
                'xaxis':{
                    'title':'Boards'
                },
                'yaxis':{
                     'title':'Data consumption'
                }
              
            }
# Change the bar mode
fig.update_layout(barmode='stack')


app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True)

Output

Styling Layout

You can customize your layout by adding some CSS to it for giving a more poised look. I will show you how to change the background colour, paper colour, and font colour. If you wish you can add any CSS styling to it. You could also add custom fonts and much more.

Basic Styling

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = {
    'paper':'#66677d',
    'background': '#111111',
    'text': '#7FDBFF'
}
.
.
.
.
.
.
.
.
.
    'layout': {
                'title': 'Energy Usage Analysis ',
                 'plot_bgcolor': colors['background'],
                'paper_bgcolor': colors['paper'],
                'font': {
                    'color': colors['text']
                }
            }

Here, I have added background colour for plot and paper. Plot background defines the background of the plotting area and the paper background stands for the background of the chart. Instead of using colour code every time, you can define the colours in one place and use it everywhere. That simplifies the code and reduce duplication. Voila!

I am not that good at designing, but I have added some random colors for your understanding. The black color is your plot background and the grey area is the paper background. The font color is also applied to it.

Add Hover Text

Adding a hover text will give user a better understanding on the values and better visualisation experience.

import plotly.express as px
import plotly.graph_objects as go # or plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

data = px.data.gapminder()
boards=['Arduino', 'Raspberry Pi', 'BeagleBone']

fig = go.Figure(data=[
    go.Bar(name='Sector 1', x=boards, y=[20, 14, 23],hovertext=['27%^ than last usage', '4%^ than last usage', '19%^ than last usage']),
    go.Bar(name='Sector 2', x=boards, y=[12, 18, 29],hovertext=['16%^ than last usage', '45%^ than last usage', '5%^ than last usage'])
])
# Change the bar mode
fig.layout={
                'title': 'Overall Data Consumption Chart',
                'xaxis':{
                    'title':'Boards'
                },
                'yaxis':{
                     'title':'Data consumption'
                }
              
            }
fig.update_layout(barmode='stack')


app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True)

Here you can see that I have passed a list in ‘hovertext’ so that the values we passed will appear in the Chart as we hover on that Bar Chart items.

You might also have noticed that, it is responsive as default. In short, your effort is much less when you use the dash to develop these widgets.

Output

Display Direct Label on Item

y=[20, 14, 23]

fig = go.Figure(data=[
    go.Bar(name='Sector 1', x=boards, y=y,text=y,
            textposition='auto'#You can also use 'inside' ,'outside' , 'right'
)
])

I have created a list of values for the y-axis. Passed the same value to text variable so it will display the same as labels. You can also set the text position. The auto will set the text position inside the Bar Item.

Output

Text Formatting

If you wish to have the very same size for all the text labels, you can make use of the uniformtext layout parameter. The minsize attribute sets the font size and the mode attribute sets what happens to the labels, which can’t be fit with the desired font size: either hide them or show them with overflow. In the example below, we also force the text to be outside of bars with textposition.The text template is used to represent the values to short-form, ie,1000 represents K.

import plotly.express as px
import plotly.graph_objects as go # or plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from numpy import random

data = px.data.gapminder()
x=['January','February','March','April','May','June','July','August','September','October','November','December']
y=random.randint(675675, size=(12))

fig = go.Figure(data=[
    go.Bar(name='Sector 1', x=x, y=y,),

])
# Change the bar mode
fig.layout={
                'title': 'Overall Data Consumption Chart',
                'xaxis':{
                    'title':'Boards'
                },
                'yaxis':{
                     'title':'Data consumption'
                }
              
            }
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=15, uniformtext_mode='hide')


app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True)

I have used a numpy function to generate random values. You can replace it with your actual values.

Output

Try to zoom in the chart and you will notice that the labels that do not fit in the chart will start to vanish. If you wish to show it overlaps, you can just change the mode to show.

Rotate Label

You can rotate the label to any angle you wish, based on the input you enter.

fig.update_layout(barmode='group', xaxis_tickangle=-45)

Change Colour of Individual Bars

colors = ['#3260a8',] * 10
colors[1] = 'crimson'
colors[5] = 'green'
colors[9] = '#fff200'
data = px.data.gapminder()
x=['Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Netherlands','New Zealand']

y=random.randint(675675, size=(10))

fig = go.Figure(data=[
    go.Bar(name='Sector 1', x=x, y=y,text=y,marker_color=colors),

])

It’s possible to pass a single or an iterating list of colors to marker_color property.

Output

Conclusion

So yes, we have learned about generating Bar graphs using Dash. In the next tutorial you will get to learn how to create scatter plots using Dash.

Feel free to comment on any suggestions or opinions in the feedback section. And if you find this particularly helpful and informative share it with your friends as well.

Until next time, Happy Coding Folks!😊

How useful was this post?

Click on a starts to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow me on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

%d bloggers like this: