Cheat Codes to Better Visualisations with Plotly Express | by Ahilan Srivishnumohan | Towards Data Science

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.
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, sizegapminder = px.data.gapminder() #country, continent , year, lifeExp, pop, gdpPercap, iso_alpha, iso_numgapminder_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_idelection = px.data.election() #district, Coderre, Bergeron, Joly, total, winner, result, district_id
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()
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()
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()
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.
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()
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()
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.
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 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()
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()
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.
More simple code for bar charts.
fig = px.bar(gapminder_canada, #dataframe             x = ’year’,       #x-values column             y = ’pop’         #y-values column             )fig.show()
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()
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.
fig = px.bar(tips,               #dataframe             x = ”sex”,          #x-values column             y = ”total_bill”,   #y-values column             color = ”smoker”,   #column shown by color             barmode = ”group”,  #separate filter (smoker)             facet_row = ”time”, #name of grid row             facet_col = ”day”,  #name of grid column             category_orders= {“day”: [“Thur”, “Fri”, “Sat”, “Sun”],                               “time”: [“Lunch”, “Dinner”]}                                 #grid arrangement             )fig.show()
We have five columns of the dataset that we can observe, accompanied with some interactivity. By using row and column facets we have a grid layout for days of the week and time of meal; consisting of smaller bar charts which contains a summary of the type of person (smoker and sex) and their total bill.
Let’s get 3D. Here we are looking at the election dataset where the votes and outcomes of three candidates running for Mayor in Montreal are compared by the district.
fig = px.scatter_3d(                    election,                #dataframe        x = ”Joly”,              #x-values column        y = ”Coderre”,           #y-values column        z = ”Bergeron”,          #z-values column        color = ”winner”,        #column shown by color        size = ”total”,          #column shown by size        hover_name = ”district”, #hover title        symbol = ”result”,       #column shown by shape        color_discrete_map = {“Joly”: “blue”, “Bergeron”: “green”,                                “Coderre”:”red”}                                 #specific colors for x,y,z values            )fig.show()
Combined with Plotly’s hover interactivity this plot manages to display all the information from the election dataset.
Geographical charts are used in more unique situations but can also be easily done using Plotly Express.
fig = px.scatter_geo(gapminder,               #dataframe                     locations = ”iso_alpha”, #location code                     color = ”continent”,     #column shown by color                     hover_name = ”country”,  #hover info title                      size = ”pop”,            #column shown by size                     animation_frame = ”year”,#column animated                     projection = ”orthographic”#type of map                     )fig.show()
We have a very useful addition to the visualisation; which is the animation interactability. For this dataset I have chosen the year as the animation frame; so we can either autoplay throughout the years or manually select the years.
Although the above globe shaped visualisation is interesting to look at, the following map visualisation will be better for a person to observe and analyse the information.
fig = px.choropleth(gapminder,                #dataframe                    locations = ”iso_alpha”,  #location code                    color = ”lifeExp”,        #column shown by color                    hover_name = ”country”,   #hover info title                    animation_frame = ”year”, #column animated                    range_color = [20,80]     #color range                    )fig.show()
Now we have a very clear visualisation showing life expectancy around the world over time.
The animated scatter plot (a bubble chart) is my favourite visualisation, as it explains the information well and it is very dynamic.
px.scatter(gapminder,                  #dataframe          x = "gdpPercap",             #x-values column          y = "lifeExp",               #y-values column          animation_frame = "year",    #column animated          animation_group = "country", #column shown as bubble          size = "pop",                #column shown by size          color = "continent",         #column shown by color          hover_name = "country",      #hover info title          log_x = True,                #use logs on x-values          size_max = 55,               #change max size of bubbles          range_x = [100,100000],      #axis range for x-values          range_y = [25,90]            #axis range for y-values          )
So, using Plotly Express we can make great visualisations with interactability, that don’t require more than a few intuitive lines of code.