Python Dash: How to Build a Beautiful Dashboard in 3 Steps

Python Dash: How to Build a Beautiful Dashboard in 3 Steps

https://ift.tt/2Kx8Arx

Data visualization is an important toolkit for a data scientist. Building beautiful dashboards is an important skill to acquire if you plan to show your insights to a C-Level executive. In this blog post you will get an introduction to a visualization framework in Python. You will learn how to build a dashboard from fetching the data to creating interactive widgets using Dash – a visualization framework in Python.

Introduction to Dash

The dash framework can be divided into two components

  1. Layouts: Layout is the UI element of your dashboard. You can use components like Button, Table, Radio buttons and define them in your layout.
  2. Callbacks: Callbacks provide the functionality to add reactivity to your dashboard. It works by using a decorator function to define the input and output entities. 

In the next section you will learn how to build a simple dashboard to visualize the marathon performance from 1991 to 2018. 

Importing the libraries

Let us first import all the import libraries

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_split_pane
import plotly.express as px
import pandas as pd
from datetime import datetime

We are importing the pandas library to load the data and the dash library to build the dashboard. 

The plotly express library is built on top of ploty to provide some easy-to-use functionalities for data visualization.

First we will begin by downloading the data. The data can be accessed on Kaggle using the following link   

Step 1: Initializing a Dash App

We start by initializing a dash app and using the command run_server to start the server.

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
 
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
 
 
if __name__ == '__main__':
   app.run_server(debug=True)

Step 2: Building the Layout

We will start by dividing our UI layer into two parts  – the left pane will show the settings window which will include an option to select the year. The right pane will include a graphical window displaying a bar plot.

app.layout = html.Div(children=[
   html.H1(children='World Marathon Analysis',
    style={'textAlign': 'center'}),
  
   dash_split_pane.DashSplitPane(
   children=[
  
   html.Div(children=[
        html.H1(children='Settings', style={'textAlign': 'center'}),
           ], style={'margin-left': '50%', 'verticalAlign': 'middle'}),
   html.Div(children=[
        html.H1(children='Graph View', style={'textAlign': 'center'}),
            ])
   ],
   id="splitter",
   split="vertical",
   size=1000,
)
  
])

We construct two div elements- one for the left pane and the other for the right pane. To align the header elements to the center we use the style tag and using standard CSS syntax to position the HTML elements.

If you now start the server and go to your browser on localhost:8050, you will see the following window.

Step 3: Creating the Dropdown Widget and the Graphical Window

Once we have the basic layout setup we can continue with the remaining parts.

Loading the Data  

We begin by loading the data using the pandas library

def convert_to_time(time_in_some_format):
   time_obj =  datetime.strptime(time_in_some_format, '%H:%M:%S').time()
   return time_obj
 
def get_data():
  df = pd.read_csv('world_marathon_majors.csv', engine="python")
  df['time'] = df['time'].apply(convert_to_time)
  return df

We create two functions to load the data and convert the time value to datetime object values.

The table below shows the first five rows of the dataset.

Every row consists of

  1. The Year the marathon took place
  2. The winner of the marathon in that year
  3. The gender of the winner
  4. The country the winner represents
  5. The time to finish the race
  6. The country in which the marathon took place.

Extending the Layout

The next step is to extend our layout layer by adding the dropdown widget and the graphical window.

app.layout = html.Div(children=[
   html.H1(children='World Marathon Analysis',
    style={'textAlign': 'center'}),
  
   dash_split_pane.DashSplitPane(
   children=[
  
   html.Div(children=[
        html.H1(children='Settings', style={'textAlign': 'center'}),
        dcc.Dropdown(id='dropdown-menu', options=[{'label':x, 'value': x} for x in range(df['year'].min(), df['year'].max()+1)],
         value=df['year'].max(),
         style={'width': '220px','font-size': '90%','height': '40px',}
        )
    ], style={'margin-left': '50%', 'verticalAlign': 'middle'}),
   html.Div(children=[
        html.H1(children='Graph View', style={'textAlign': 'center'}),
        dcc.Graph( id='input-graph',figure=get_default_data())
    ]) 
   ],
   id="splitter",
   split="vertical",
   size=1000,
)
])

We give the dropdown widget a unique id called dropdown-menu and the graphical window is given an id input-graph. 

Callbacks

Callbacks are used to enable communication between two widgets. 

We define a function called update_output_div which takes the year value whenever the dropdown menu is changed. On every change in the dropdown value the function update_output_div is executed and a bar plot is drawn to indicate the top countries which won the race.

@app.callback(
   dash.dependencies.Output('input-graph', 'figure'),
   [dash.dependencies.Input('dropdown-menu', 'value')]
)
def update_output_div(value):
   test_sample = df[df['year'] == value]
   test_sample = test_sample.groupby('country')['time'].min().reset_index()
   tt = test_sample.sort_values(by=['time'])
   fig = px.bar(tt, y='country', x='time', orientation='h', hover_data=["time"], )
   return fig

Live Demo

Let us now see the dashboard in action.

In this blog post you learned how to build a simple dashboard in Python. You can extend the above dashboard to include more widgets and displaying more graphs for further analysis.

The post Python Dash: How to Build a Beautiful Dashboard in 3 Steps first appeared on Finxter.

Python

via Finxter https://ift.tt/2HRc2LV

December 28, 2020 at 10:59AM

2-Acre Vertical Farm Run By AI and Robots Out-Produces 720-Acre Flat Farm

2-Acre Vertical Farm Run By AI and Robots Out-Produces 720-Acre Flat Farm

https://ift.tt/3rxeZDx

schwit1 quotes Intelligent Living: Plenty is an ag-tech startup in San Francisco, co-founded by Nate Storey, that is reinventing farms and farming. Storey, who is also the company’s chief science officer, says the future of farms is vertical and indoors because that way, the food can grow anywhere in the world, year-round; and the future of farms employ robots and AI to continually improve the quality of growth for fruits, vegetables, and herbs. Plenty does all these things and uses 95% less water and 99% less land because of it. Plenty’s climate-controlled indoor farm has rows of plants growing vertically, hung from the ceiling. There are sun-mimicking LED lights shining on them, robots that move them around, and artificial intelligence (AI) managing all the variables of water, temperature, and light, and continually learning and optimizing how to grow bigger, faster, better crops. These futuristic features ensure every plant grows perfectly year-round. The conditions are so good that the farm produces 400 times more food per acre than an outdoor flat farm. Another perk of vertical farming is locally produced food. The fruits and vegetables aren’t grown 1,000 miles away or more from a city; instead, at a warehouse nearby. Meaning, many transportation miles are eliminated, which is useful for reducing millions of tons of yearly CO2 emissions and prices for consumers. Imported fruits and vegetables are more expensive, so society’s most impoverished are at an extreme nutritional disadvantage. Vertical farms could solve this problem.


Read more of this story at Slashdot.

geeky

via Slashdot https://slashdot.org/

December 27, 2020 at 07:28PM

A question from my childhood answered

A question from my childhood answered

https://ift.tt/3nPQIGt

I saw this posted at Wirecutter’s.

I grew up with the audiobooks of James Herriot’s All Creatures Great and Small series, narrated by Christopher Timothy, who played James Herriot MRCVS in the BBC series (which I also love).

A few times n the book series, James mentions having to put down an animal with a humane killer.  I never knew that was a specific device until I saw this video.

I found this extremely interesting because it answered a question from my childhood that I never knew I had.

guns

via https://gunfreezone.net

December 26, 2020 at 06:25AM

How Gift Wrapping Paper is Made: Rotary Screen Printing

How Gift Wrapping Paper is Made: Rotary Screen Printing

https://ift.tt/2KvoT85

If you thought gift wrapping paper was wasteful as an end product, wait ’til you see the production method. In rotary screen printing, each color requires its own copper cylinder:

Source

Here’s a more in-depth look at how the process works:

I’ll stick with newspaper.

fun

via Core77 https://ift.tt/1KCdCI5

December 23, 2020 at 12:49PM

CMMG Releases Shortest and Most Compact BANSHEE .22LR AR-15

CMMG Releases Shortest and Most Compact BANSHEE .22LR AR-15

https://ift.tt/34CMB96

CMMG Releases Shortest and Most Compact BANSHEE .22LR AR-15
CMMG Releases Shortest and Most Compact BANSHEE .22LR AR-15

U.S.A.-(AmmoLand.com)- CMMG is proud to introduce the shortest and most compact BANSHEE to date. This new line-up is chambered in .22LR and features a capped lower receiver with no buffer tube (receiver extension).

This ultra-compact BANSHEE is made possible by CMMG’s new .22LR End Cap – which is a new way to transform your .22LR AR15 build.

The .22LR End Cap is the perfect accessory that shortens your .22LR AR15 by replacing the need for a receiver extension and buffer assembly. The .22LR End Cap is compatible with all CMMG .22LR AR Conversion Kits, as well as any AR15 that uses a dedicated CMMG .22LR bolt carrier group and barrel.

The .22LR End Cap is available in two variations: standard, with a smooth exterior and CMMG logo (.22LR End Cap LOGO), and QD (quick-detach), which has an attachment point machined into the exterior for attaching a QD sling. Installing the .22LR End Cap is made easy by securing the .22LR End Cap on the back of the lower receiver with a 3/8” hex wrench, in lieu of the buffer tube.

The .22LR End Cap with CMMG logo can be purchased separately for $24.95 and the QD End Cap for $29.95.

.22LR End Cap with CMMG logo (left) QD End Cap (Right)
.22LR End Cap with CMMG logo (left) QD End Cap (Right)

BANSHEE lower groups and complete BANSHEE .22LR pistols are offered with the .22 LR End Cap preinstalled: the BANSHEE 100 Series comes with the .22 LR End Cap LOGO and the BANSHEE 200 and 300 Series come with the QD End Cap. MSRP on the complete BANSHEE pistols range from $799.95 to $1,024.95.

For more information on the .22LR End Cap and all BANSHEE models, please visit www.CMMGinc.com.

CMMG Guarantee:

All CMMG products are covered under the CMMG Lifetime Quality Guarantee. Conditioned on being a Limited Warranty of use, maintenance, and cleaning of the product in accordance with CMMG, Inc.’s instructions to be free of defects in material and workmanship. CMMG will repair, replace or substitute part(s) as determined in the sole and absolute discretion of CMMG Inc at no charge to the purchaser or provider. Complete limited warranty information can be found at CMMGinc.com/tech-support


About CMMG:

CMMG began in central Missouri in 2002 and quickly developed into a full-time business because of its group of knowledgeable and passionate firearms enthusiasts committed to quality and service. Its reputation was built on attention to detail, cutting edge innovation and the superior craftsmanship that comes from sourcing all their own parts. By offering high quality AR rifles, parts and accessories, CMMG’s commitment to top-quality products and professional service is as deep today as it was when it began.

For more information, visit CMMGinc.comCMMG logo

The post CMMG Releases Shortest and Most Compact BANSHEE .22LR AR-15 appeared first on AmmoLand.com.

guns

via AmmoLand.com https://ift.tt/2okaFKE

December 23, 2020 at 01:07PM

Laravel Python Package

Laravel Python Package

https://ift.tt/3nHOtoy


LaravelPython

Execute Python scripts inside your Laravel Application.

Installation

composer require robertogallea/laravel-python

Configuration

To edit the default package configuration, publish the config resource with the command

php artisan vendor:publish --provider="robertogallea\LaravelPython\ServiceProvider" --tag=config

then edit config/laravel-python.php

Usage

You can run commands in several ways:

  1. Instantiating LaravelPython service:
use robertogallea\LaravelPython\Services\LaravelPython;
...

$service = new LaravelPython();
$result = $service->run('/path/to/script.py'):
$parameters = array('par1', 'par2'):
$result = $service->run('/path/to/script.py', $parameters):
  1. Injecting from the ServiceContainer
use robertogallea\LaravelPython\Services\LaravelPython;
...
public function __construct(LaravelPython $service)
{
  $result = $service->run('/path/to/script.py')
  $parameters = array('par1', 'par2'):
  $result = $service->run('/path/to/script.py', $parameters):
}
  1. Using the Python facade
$result = \Python::run('/path/to/script.py')
$parameters = array('par1', 'par2'):
$result = \Python::run'/path/to/script.py', $parameters):
  1. Via command line with an artisan command
php artisan python:run /path/to/script.py "Some parameter"

Note that you can use an arbitrary number of parameters

Issues, Questions and Pull Requests

You can report issues and ask questions in the issues section. Please start your issue with ISSUE: and your question with QUESTION:

If you have a question, check the closed issues first. Over time, I’ve been able to answer quite a few.

To submit a Pull Request, please fork this repository, create a new branch and commit your new/updated code in there. Then open a Pull Request from your new branch. Refer to this guide for more info.

programming

via Laravel News Links https://ift.tt/2dvygAJ

December 21, 2020 at 08:42PM

Carol of the Mandalorian

Carol of the Mandalorian

https://ift.tt/3h5pvgA

Carol of the Mandalorian

Link

We might not be getting a Mandalorian holiday special any time soon, but if we ever do, we already have the theme song. AtinPiano’s mashup of Ludwig Göransson’s epic Mando score with the Christmas classic Carol of the Bells would fill the bill perfectly. They previously gave The Imperial March the holiday treatment.

fun

via The Awesomer https://theawesomer.com

December 21, 2020 at 05:45PM

untitled

untitled

https://ift.tt/3h3Hbt0

The season of gift-giving can cause a lot of stress as you worry about what to get, and how much it’s going to cost. Use these free sites to discover the best gifts to give while staying within your budget.

With the help of technology, there are some ingenious ways to find the best gift to give someone. Smart algorithms can analyze people’s Instagram profiles to uncover what they’ll like. You can create wishlists to share with friends or look through catalogs based on who you’re shopping for and their interests. And all while using tactics to save money.

1. Matchbox (Web): Match Person and Interests to Find Amazon Recommendations


Matchbox is a simple, easy-to-browse gift recommendation engine. In a three-step process, it shows curated gift ideas based on who you’re shopping for.

In the first step, select the person, such as a friend, sister, grandfather, mother, etc. Then add their age. In the second step, select that person’s primary interest from categories like organization, creativity, sports, etc.

Matchbox will then display a list of gift ideas, all of which are available on Amazon. You can filter this list further by price range or categories (i.e. Amazon store categories). Click the Heart to add anything that looks interesting to your wishlist for later. And you can quickly restart the search too, while your wishlist is stored.

2. Wishy.gift (Web): Create a Wishlist to Share With Close Friends

Image Gallery (2 Images)

Wishy.gift lets you create a wishlist of things you want, with links, and share them with friends
Expand
Participants in a Wishy.gift list can claim items they're buying as gifts
Expand

If you’re exchanging gifts with your family or a small group of friends, Wishy.gift’s shared wishlists will make shopping easier. It’s a simple free web app to add and claim items.

Once you register for an account, you can create a wishlist and share it with friends. Each item in the wishlist has space for a name or description and a link, which will make it easier for friends to buy the right item. You can also add multiple numbers of an item (like five pairs of socks) so that different people can claim one each.

As a recipient of a list, you can claim a gift idea so that there aren’t repeats. You can also see which items have already been claimed by others. It’s a remarkably easy mechanism to understand.

Wishy.gift is great for small groups where everyone is gifting everyone else. You can also use it for charities or donation drives, to lend a helpful hand during the holidays.

3. Random Gift Idea (Web): Tinder for Gifts


Can’t think of what gift to get for someone? Random Gift Idea has plenty of suggestions in a mobile-friendly website, using a Tinder-like interface where you swipe to discover more.

Swipe left to discard the current item for a new one. Swipe right to add an item to your wishlist. And find out more about any item by clicking the button to go to the product page.

Random Gift Idea has a few filters to narrow down the selection. You can set a price range from zero to 1000 dollars. And you can choose recipients like men, women, teen, baby, kids 4-7, and kids 8-12. It’s a fun way to window shop for the coolest things online.

4. Gifthub (Web): Gift Ideas Based on Instagram Profiles


People let out more about themselves on their social media profiles than they think. Gifthub analyzes a person’s Instagram profile to recommend gifts that they are bound to like. Just enter the username and let Gifthub work its magic. The products link to Amazon USA, and generally include an affiliate link.

You should get the username right otherwise Gifthub won’t work. The company also doesn’t explain how it arrives at the list of recommended products. When we tested it with our MakeUseOf Instagram account, it needed additional input on gender and age. That input wasn’t needed with personal accounts.

Gifthub also has a Telegram bot to help you pick gifts for friends. It’s a step-by-step chat based on multiple-choice answers, which will help Gifthub arrive at a suitable recommendation.

5. Wanderkind (Web): Creative Gifts to Educate and Entertain, for Kids and Adults


You can’t predict the impact that your gift will have. Gift a child their first set of watercolors and a paintbrush, and you might just inspire the next Picasso. Your aunt always loved music, and a harmonica might be the gift that unlocks unbridled joy in her. These are the types of gifts that entertain, educate, and delight. That’s what Wanderkind is all about.

Wanderkind collects gift ideas that focus on discovery, movement, learning, and creativity. It’s a carefully selected list of items that are built to last ("no cheap plastic" is a rule they adhere to), are a lot of fun for all ages, and spark an innate joy.

That said, Wanderkind is careful to pick items that look good as gifts, and aren’t simply utility pieces. For example, for a fantasy book lover, they recommend a well-crafted box set of The Lord of the Rings books. The gifts have a wide price range and come in a variety of categories.

6. How to Set Up a Christmas Budget (Web): Dave Ramsey’s Money Saving Advice


If you aren’t mindful of how much you are spending on each gift, you can quickly run over budget. In fact, credit card company reports show people taking on big debts during this time. If you want to save money over the holiday season, take personal finance guru Dave Ramsey’s advice on how to set up a Christmas budget.

In his blog post, Ramsey recommends making a zero-based budget. This means you won’t take on any debt, and includes tips like setting up a Christmas fund, tweaking budget lines, and being meticulous.

As usual, Ramsey recommends his app EveryDollar to put this into practice, but you can use any expense tracker or budgeting app. It’s universal advice that you could even put into use with a pen and paper.

A Digital, Distanced Christmas?

The COVID-19 pandemic forced the world indoors in 2020. With lockdowns, quarantines, and self-isolation, we have had to rethink how we celebrate holidays and go about our daily lives. Will this be a digital, socially distanced Christmas too?

However you choose to celebrate it, there are enough ways to make it enjoyable. More and more, people are finding solace through our digital world, whether it’s video chat parties or sharing your recipes online. And you can always exchange gifts digitally on Christmas morning too.

non critical

via MakeUseOf.com https://ift.tt/1AUAxdL

December 21, 2020 at 04:36AM

Memes that made me laugh 37

Memes that made me laugh 37

https://ift.tt/3ax2C4u

 

Harvested over the past week from around the Internet.

And, not funny, but more true than not, IMHO:

True dat.

Peter

non critical

via Bayou Renaissance Man https://ift.tt/1ctARFa

December 21, 2020 at 04:50AM

Laravel Desktop Notifier

Laravel Desktop Notifier

https://ift.tt/3aAnuaT


Laravel Desktop Notifier is a package by Nuno Maduro to send notifications to your desktop from Artisan commands:

public function handle()
{
    $this->notify('Hello Web Artisan', 'Love beautiful code? We do too!');
    // Icons anyone?
    $this->notify(
        'With a logo!',
        'This has a logo',
        resource_path('path/to/icon.png')
    );    
}

The first example would look something like this on macOS:

Under the hood, this package uses the a macro to add the notify method to console commands:

Command::macro('notify', function (string $text, string $body, $icon = null) {
    $notifier = $this->laravel[Contracts\Notifier::class];

    $notification = $this->laravel[Contracts\Notification::class]
        ->setTitle($text)
        ->setBody($body);

    if ( ! empty($icon)) {
        $notification->setIcon($icon);
    }

    $notifier->send($notification);
});

As you can see, the first argument is the notification title, followed by the notification body and the optional icon.

If you’re interested in integrating desktop notifications in a PHP package, this package uses the excellent JoliNotif. Desktop notifications work across Linux, Windows, and macOS!

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:
News
/
laravel
/
packages

programming

via Laravel News https://ift.tt/14pzU0d

December 21, 2020 at 09:14AM