Cheat Codes to Better Visualisations with Plotly Express
By: Ahilan Srivishnumohan
Tags: Data Visualization, Plotly, Guides And Tutorials, Interactive, Python

Cheat Codes to Better Visualisations with Plotly Express

Two of the most popular libraries used for visualisations in Data Science is Matplotlib and Seaborn. I want to show how using the Plotly Express module from the Plotly library we can get the simplicity of Seaborn and Matplotlib, but achieve a more in-depth and interactive visualisation.

Plotly Express is an easy-to-use and a high-level interface of the Plotly library. So, let’s have look at how we can get started.

Imports

import plotly.express as px

Let’s look at some datasets already in the Plotly Express module:

tips = px.data.tips()

#total_bill, tip, sex, smoker, day, time, size gapminder = px.data.gapminder()

#country, continent , year, lifeExp, pop, gdpPercap, iso_alpha, iso_num gapminder_canada = gapminder.query("country=='Canada'")

gapminder_oceania = gapminder.query("continent=='Oceania'")

gapminder_continent = gapminder.query("continent != 'Asia'") iris = px.data.iris()

#sepal_length, sepal_width, petal_length, petal_width, species, species_id election = px.data.election()

#district, Coderre, Bergeron, Joly, total, winner, result, district_id

Histogram

Let’s look at the tips dataset using histograms because the data includes a lot of categorical variables. For the first one, I’ll use the total bill as the variable to plot as a histogram.

fig = px.histogram(tips, #dataframe

x = "total_bill", #x-values column

nbins = 30 #number of bins

)

fig.show()

Histogram of Total Bill Price

With Plotly Express we can create an interactive histogram. We can see the bin range by the x-axis, the total_bill value, and the count at each point when hovering the cursor.

Let’s level up our histograms by considering a second variable, sex:

fig = px.histogram(tips, #dataframe

x = ”total_bill”, #x-values column

color = ”sex” #column shown by color

)

fig.show()

Histogram of Total Bill Price Relative to Sex

Now we can see both male and female count for total bill, but on top of the hovering interactivity, we can also isolate the histogram to show either male, female, or both.

Another minor update to a histogram can be adding a rug plot, a box plot, or a violin plot:

fig = px.histogram(tips, #dataframe

x = ”total_bill”, #x-values column

color = ”sex”, #column shown by color

marginal = ”rug”, #plot type (eg box,rug)

hover_data = tips.columns #extra info in hover

)

fig.show()

Histogram of Total Bill Price Relative to Sex Including Rug Plot of Datapoints

Here I have used a rug plot and now we can see the data points relative to the bins below in the histogram. As you may be wondering, you can interact with the rug plots as well.

Scatter Plot

Another popular and effective visualisation type that Plotly Express not only simplifies yet enhances, is the scatter plot. Here we are looking at the iris dataset; which is about the sizes of different plant species.

fig = px.scatter(iris, #dataframe

x = "sepal_width", #x-values column

y = "sepal_length" #y-values column

)

fig.show()

Scatter Plot of Septal Width and Septal Length

We can make this scatterplot more dynamic and informative by adding colour, size, and more interactive data.

fig = px.scatter(iris, #dataframe

x = ”sepal_width”, #x-values column

y = ”sepal_length”, #y-values column

color = ”species”, #column shown by color

size = ’petal_length’, #col shown by plotsize

hover_data = [‘petal_width’] #extra info in hover

)

fig.show()

Scatter Plot of Septal Width and Septal Length (with Colour = Species and Size = Petal Length)

Having the ability to isolate or group the plants by species on one set of axis with the addition of different colours helps us from having to create three individual plots for comparison.

Line Graph

A traditional line graph is also very simple with Plotly Express.

fig = px.line(gapminder_canada, #dataframe

x = "year", #x-values column

y = "lifeExp" #y-values column

)

fig.show()

Line Graph of Life Expectancy of Canadians over a 60 Year span

Line graphs are great for comparing two rows from a dataset, and this can be done by adding one more attribute to the plot. In this case, colour for country.

fig = px.line(gapminder_oceania, #dataframe

x = "year", #x-values column

y = "lifeExp", #y-values column

color = 'country' #column shown by color

)

fig.show()

Line Graph of Life Expectancy of Australians and Kiwis over a 60 Year span

Here we have two countries from Oceania so they were both allocated a colour, without having to mention the names of the countries, but only the column name for the argument of colour.

We can add more continents other than Oceania, but how do we keep graph from becoming overwhelming?

Showing the continent as the colour then setting the line group as the country, allows us to visualise the life expectancy in different continents without having to average the life expectancy for all the countries within that continent.

fig = px.line(gapminder_continent, #dataframe

x = ”year”, #x-values column

y = ”lifeExp”, #y-values column

color = ”continent”, #column shown by color

line_group = ”country”, #group rows of a column

hover_name = ”country” #hover info title

)

fig.show()

Line Graph of Life Expectancy of Countries Around the World over a 60 Year span (Excluding Asia)

Once again we can isolate lines of the continents if individual observations are preferred, as well as a hover ability to check the country represented by each line.

Bar Chart

More simple code for bar charts.

fig = px.bar(gapminder_canada, #dataframe

x = ’year’, #x-values column

y = ’pop’ #y-values column

)

fig.show()

Bar Chart of the Population of Canada over a 60 Year span

We can add more information about the change in population throughout time in Canada, by including life expectancy using colour. Upgrade axis label pop to population of Canada, using the labels attribute of bar charts, and also add more detail to the hover function.

fig = px.bar(gapminder_canada, #dataframe

x = ’year’, #x-values column

y = ’pop’, #y-values column

hover_data = [‘lifeExp’, ‘gdpPercap’],#extra hover info

color = ’lifeExp’, #column by color

labels = {‘pop’:’population of Canada’}#label change

)

fig.show()

Bar Chart of the Population of Canada over a 60 Year span (with Colour = Life Expectancy)

Above, we can depict two trends about the Canadian population over time with one graph effectively.

Looking back at the tips dataset, we could stack a lot more information into a bar chart visualisation.