Skip to content

Latest commit

 

History

History
204 lines (179 loc) · 6.64 KB

File metadata and controls

204 lines (179 loc) · 6.64 KB

Bar Charts

Bar charts are charts use rectangles represent data values for each attribute. In this folder, we will go over how to create bar charts with Python and Plotly.

Files

The following scripts are used in this chapter:

  • Simplebar.py
  • Groupbar.py
  • Stackbar.py

Pacakges Needed

This chapter requires the following packages for the scripts used:

  • Pandas
  • Plotly

Data Used

This chapter may use the following data from the Data folder:

  • salary.csv
  • expense_everybody.csv

Syntax

Data

Data is a list of go.Bar(), each go.Bar() represents a category of bars.

If the data list has only 1 go.Bar(), it is a simple bar chart: Each attribute has only 1 bar.

If it is grouped, each attribute has a group of bars displayed (All bars belong to each attribute stick together) ordered by the order in the data list.

If it is stacked, each attribute has one bar, each category value would be stacked on top of other categories order by the the order in the data list.

go.Bar() has the following parameters:

  • x: Attribute on x-axis
  • y: Value on y-axis
  • name: Category, which will be displayed on legend
  • text: The text label will displayed on the bars
  • textposition: Text label position
    • auto: On the top of the bar
    • inside: On the top of the bar
    • outside: Outside of the bar
  • orientation: Orientation, use 'h' to indicate horizontal bars
  • textfont (Dictionary): Text label setting
  • marker_color: Bar colour (Take colour spelliing in string or RGB in string)
  • width: Width of the bar in pixel
  • hoverinfo: What information to be displayed when user hover over the bar, all the options are:
    • all (Default)
    • none/skip (Both keywords in string means no hovering)
    • percent
    • label+percent
    • label
    • name
    • text
  • hovertemplate: The information to be displayed when user hover over the bar, defined in HTML format

Layout

Genetic Layout parameters suggested to use:

  • title (Dictionary): Chart title and fonts
    • text: Chart title to be displayed
    • x: text location on x-dimension, from 0-1
    • y: text location on y-dimension, from 0-1
  • xaxis (Dictionary): X-axis setting
    • tickmode: Setting of ticks
    • tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
    • categoryorder: Sort the order of attributes on X-axis, either ascending or descending
      • category ascending: Sort attribute (attribute in name in Data) in ascending orders
      • category descending: Sort attribute (attribute in name in Data) in descending orders
      • total ascending: Sort value in ascending orders
      • total descending: Sort value in descending orders
      • min ascending/min descending: Sort by minimum value
      • max ascending/max descending: Sort by maximum value
      • sum ascending/sum descending: Sort by summation value
      • mean ascending/mean descending: Sort by average value
      • median ascending/median descending: Sort by median value
      • array: Follow the sorting order defined in categoryarray
    • categoryarray: Define the sorting order when categoryorder is array
  • yaxis (Dictionary): y-axis setting
    • tickmode: Setting of ticks
    • tickangle: Degree the tick rotate (-: Anticlockwise, +: Clockwise)
  • barmode: How the bars are grouped (See below for detail)
  • uniformtext (Dictionary): Allow bar chart becomes Marimekko Chart by forcing bars to stick together
    • mode: Put "hide" to becomes Marimekko chart
    • minsize: Minimum size of bars


Bar Chart Exclusive parameters:

  • barmode: How the bars are grouped
    • grouped: Bars stick together if they belong to the same attribute
    • stacked: Bars stack on top of each other if they belong to the same attribute
    • relative: Stacked bars, but negative values stack below 0
  • marker_color: Bar colour

Examples

Example 1 - Simple Bar Chart

# Data
data = []
data.append(go.Bar(x=df['name'], y=df['salary'],
	               text=df['salary'], textposition='auto',
	               textfont=dict(color='white')))
# Layout
layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}

Example 2 - Grouped Bar Chart

data =[]
for cate, colour, width in zip(df['expense_category'].unique(),colours, widths):
	df_temp = df[df['expense_category']==cate]
	data.append(go.Bar(name=cate, 
	               x=df_temp['name'], y=df_temp['amount'],
	               marker_color=colour,
	               width=[width]*len(df_temp['name']),
	               text=df_temp['amount'], textposition='auto',
	               textfont={'color':'white'}))

fig_title = 'Everybody\'s Expense'
layout = dict(title={'text':fig_title, 'x':0.5},
              barmode='group', 
              xaxis=dict(tickmode='linear',tickangle=-45))

Each bar is a stored as an element in data list, and set barmode to group.

Example 3 - Stacked Bar Chart

# Prepare data
data =[]
for cate in df['expense_category'].unique():
	df_temp = df[df['expense_category']==cate]
	data.append(go.Bar(name=cate, 
	               x=df_temp['name'], y=df_temp['amount'],
	               text=df_temp['amount'], textposition='auto',
	               textfont=dict(color='white')))

fig_title = 'Everybody\'s Expense'
layout = dict(title={'text':fig_title, 'x':0.5},
              barmode='stack', 
              xaxis=dict(tickmode='linear',categoryorder='total descending'))


Each bar is a stored as an element in data list, and set barmode to stack.

Example 4 - Horizontal Bar Chart

# Data
data = []
data.append(go.Bar(y=df['name'], x=df['salary'],
	               text=df['salary'], textposition='auto',
	               orientation='h',
	               textfont=dict(color='white')))
# Layout
layout = {'title':{'text':'Everybody\'s Salary', 'x':0.5}}

Besides adding the orientation as arguement, note that you have to swap x and y columns for this use case!

Reference

Plotly Documentation Bar Chart