Bar chart in plotly

Bar charts in plotly with bar

You can create bar plots in plotly and Python with bar, a function from plotly express. The function provides two ways for data specification: passing a data frame and specifying the values as the column names of that data frame or passing arrays as input of x and y.

For instance, consider the following data frame named df which represents five groups (group column) and their corresponding value (value column). In order to create a bar chart in plotly and Python you can type:

Bar chart with categories and values

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value')

fig.show()

Bar chart with positions and values

Note that instead of groups you can also input a numerical variable. In this scenario, the elements will represent the position where to create the bars.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    x = [1, 2, 4, 5],
    y = [14, 12, 10, 16]))

fig = px.bar(df, x = 'x', y = 'y')

fig.show()

Horizontal bar plot

It is possible to create a horizontal bar chart just switching the column names, this is, passing the categorical variable to y instead of to x.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'value', y = 'group')

fig.show()

Error bars

The bar function provides the error_y and error_x arguments to specify error bars for vertical and horizontal bar plots, respectively. You can input a column name or an array representing the standard error for each bar.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16],
    error = [0.7, 0.2, 0.4, 0.3, 0.5]))

fig = px.bar(df, x = 'group', y = 'value', error_y = 'error')

fig.show()

Title and labels

You can add a title to the plot passing a string as input to title. In addition, you can also change the axis labels with labels, which default to the column names passed as input. In order to accomplish that, you will need to create a dict where the keys are the column names passed to x and y, as in the example below.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             title = "Bar plot title",
             labels = {'group': 'Groups label', 'value': 'Values label'})

fig.show()

Colors and patterns

The color argument allows filling the bars with color based on a numerical or categorical variable. If you pass the name of a categorical variable to the argument each bar will have a different color and a legend will be displayed displaying each category.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             color = 'group')

fig.show()

Custom colors

It is possible to customize the color for each bar passing a dict of groups and colors to color_discrete_map or passing an array of ordered colors to color_discrete_sequence. Note that in order to change the colors for each group you must set color = 'group', being group the name of your categorical variable. If you want to change the color for all bars pass an array with a single color to color_discrete_sequence.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value', color = 'group',
             color_discrete_map = {'A': '#7FD4C1', 'B': '#30BFDD', 'C': '#8690FF', 
                                   'D': '#ACD0F4', 'E': '#F7C0BB'})

fig.show()

Color for all bars and border color

An alternative to change the color for all bars is with the marker_color argument from update_traces. Note that with update_traces you can customize more settings, such as the border color and width of the bars or the fill color opacity.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value')
fig.update_traces(marker_color = 'green', marker_line_color = 'black',
                  marker_line_width = 2, opacity = 1)

fig.show()

Color based on a numerical variable

If you pass a numerical variable to color the bars will be colored based on that values with a continuous color palette.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value', color = 'value')

fig.show()

Change the continuous color palette

The default continuous color palette can be customized with color_continuous_scale. You can access the full list of color palettes typing px.colors.named_colorscales(). Note that if you are using a diverging color palette you can also change the midpoint passing a number to color_continuous_midpoint.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             color = 'value', color_continuous_scale = 'viridis')

fig.show()

Pattern by group

The bar function also provides an argument named pattern_shape that behaves the same way as color, but in this case each bar will have a different pattern. Recall that you can also set color, so each bar will have a different color and pattern.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value', pattern_shape = 'value')

fig.show()

Custom patterns

It is possible to specify custom patterns for each group passing an array of patterns to pattern_shape_sequence or a dict with groups and patterns to pattern_shape_map.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value', pattern_shape = 'value',
             pattern_shape_sequence = ['x', '.', '+', '/', '.'])

fig.show()

Text labels

You can add texts to each bar in several ways. The easiest way is to set text_auto = True, which will show the values for each bar. The color of the text will also be automatic based on the fill color of the bars.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             text_auto = True)

fig.show()

Custom text

The function provides an argument named text where you can specify the name of a data frame column containing texts or an array with labels, thus, you will be able to customize the text for each bar.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16],
    text =  ['G1', 'G2', 'G3', 'G4', 'G5']))

fig = px.bar(df, x = 'group', y = 'value',
             text = 'text')

fig.show()

Text styling

Note that by using update_traces you can customize the color, position, size and angle of the texts, among other customizations, as shown in the example below.

import plotly.express as px
import pandas as pd

# Sample data
df = pd.DataFrame(dict(
    group = ["A", "B", "C", "D", "E"],
    value = [14, 12, 8, 10, 16]))

fig = px.bar(df, x = 'group', y = 'value',
             text_auto = True)
fig.update_traces(textfont_size = 14, textangle = 0, textposition = "outside")

fig.show()
Better Data Visualizations

A Guide for Scholars, Researchers, and Wonks

Buy on Amazon

See also