Step by step bar-charts using Plotly Express | by Alejandra Vlerick | Towards Data Science

As an aspiring data scientist, I love playing around with datasets and unraveling the story hidden behind the rows and columns. One of the first things I do is to visualise the data with bar charts. This allows me to get acquainted with the information and formulate a game plan for future analysis.
If you’re not already a member, get your Medium Membership here!
I decided to find a nice and simple dataset that would allow me to focus on the plotting and not on the cleaning. I found the “Married at first sight” dataset to fit my needs because it has a healthy mix of numerical and categorical data. This TV show has become a quarantine guilty pleasure. On this series, two people are randomly matched and they can decide to get married or not after vacationing for three weeks in a dream location. The dataset can be found here.
The first step is to import all the libraries I will be using. Plotly is a is a library for creating static, animated, and interactive visualisations in Python. Plotly Express is a new high-level Python visualisation library part of Plotly v.4, that allows to plot complex charts using simple syntax.
Once the libraries have been imported, I load my file using the read_csv() function and convert it to a pandas dataframe.
import pandas as pdimport plotly.express as pxfrom plotly.subplots import make_subplotsdf = pd.read_csv("Data/mafs.csv")
There are two things I do as soon as I have my pandas dataframe. Firstly, I look at the header names and the variable types stored in each column.
print(df.info())
This tells me that there are 17 columns in my dataset, some store ‘Object’ types, which I like to think of as strings and also ‘int64’ which is simply and integer stored with 64 bits.
Secondly, I look at the first row of my dataframe.
print(df.iloc[0])
By changing the index [0] to any integer I could also find the information of any row.
This tells me that in this TV show, the contestant Jamie Otis-Hehner was 27 years old at the time of the competition and a nurse in profession. More importantly, this contestant decided to get married in the TV show, and is still married today. Lucky gal!
My first instinct was to plot the number of people that agreed to get married versus those that preferred remaining single. This information is found on the ‘Decision’ column where values are ‘Yes’ or ‘No’.
df1 = df.groupby(["Decision"]).count().reset_index()fig = px.bar(df1,             y=df.groupby(["Decision"]).size(),             x="Decision",             color='Decision')fig.show()
Using the groupby() function I was able to shuffle the rows in my dataset such that they were organised by Decision outcome. The only thing left to do was to select the x-axis and y-axis that yielded the desired information.
It is clear from the graph that 70% of the contestants decide to get married after three weeks, which is a surprisingly high success rate. Maybe this is why there have been 10 seasons of the show!
The second thing I wanted to do is to see if the location influences the number of successful couples. For this, I plotted location on the x-axis and the number of ‘Yes’ and ‘No’ answers on the y-axis.
df2 = df.groupby(['Location','Decision']).size().reset_index(name='Decision_qt')df2_yes = df2[df2['Decision']=='Yes']df2_yes.set_index('Location', inplace=True)fig = px.bar(df2,             x="Location",             y="Decision_qt",             color='Decision',             barmode='stack')fig.show()
Again, using the groupby() function I group my rows by Location first and then Decision, essentially creating a group, within a group. I also create an additional column called Decision_qt, which holds the number of ‘Yes’ and ‘No’ answers per location.
Other than Chicago and Dallas (where ALL the contestants decided to get married!) we can see that the location influences lightly the success rate of the couples. At this point I would add that we are only looking at around 6 to 12 people per location, a bigger sample size would yield more reliable information...
Now, the next thing I want to look into is the number of people that divorced after getting married on the show. In order to plot this ratio, I need to follow three simple steps.
I create a dataframe ‘df_married’ that groups the rows by location and status. I also create an additional column ‘Maried_qt’ with the total number of married people in each row. Finally, I modify this dataset such that only the rows of married participants remain.
df_married = df.groupby(['Location','Status']).size().reset_index(name='Married_qt')df_married = df_married[df_married['Status']=='Married']
Now I want to count the total number of participants per location. This is achieved again by using the groupby() function and summing the rows in each group using the size() function.
df3 = df.groupby(['Location']).size().reset_index(name='Participants_qt')
In order to perform the division we first have to set the index of our two dataframes to be the Location (the ratio is taken between couples that married and divorced in the same city). The result of the division is saved in a column named ‘ratio_Married’
# Divisiondf_married.set_index('Location', inplace=True)df3.set_index('Location', inplace=True)df3['ratio_Married'] = (df_married['Married_qt'] / df3['Participants_qt'])# Plottingdf_married.reset_index(inplace = True)df3.reset_index(inplace = True)fig = px.bar(df3,             x='Location',             y='ratio_Married',             color='Location',             barmode='stack')# fig.show()
For the plotting, the corresponding Location and Ratio columns of the dataframe are selected in x-axis and y-axis respectively from dataframe df3.
This plot is less optimistic than the previous two. More than 50% of the couples that agreed to get married get divorced subsequently. In Atlanta and South Florida, not a single contestant is still married to his/her counterpart...
This took me a little while to figure out, which is why I’m super excited to share! Creating subplots can be extremely useful when trying to compare and contrast plots, or bar charts. Underlying relationships can be easily visualised when things are put side by side.
In order to make a figure with multiple subplots, the first step is to specify the number of subplots and their location. In my case, I chose to have my figures on the same row but different columns (side by side). The type “xy” indicates the coordinate system (could also be polar for example).
subfig = make_subplots(rows=1, cols=2,                    specs=[[{"type": "xy"}, {"type": "xy"}]])
Now we create two sub-plots, specify their axis and values.
This is the same as the Yes vs No bar chart at the beginning of the article. It is important to note that plotly express only supports series. This means that I need to convert the information I want to plot into a series from the pandas dataframe using the pd.Series() function.
df4 = df.groupby(["Decision"]).size().reset_index(name='Total_YesNo')y1=pd.Series(df4['Total_YesNo'])subfig.add_bar(row=1, col=1,             y=y1,             x=["Yes", "No"])
In the second figure I plot the ratio of Yes vs No answers per location. The x and y-axis values are transformed into series and this is passed onto the subfigure for plotting.
df5 = df.groupby(['Location']).size().reset_index(name='Participants_qt')x2=pd.Series(df5['Location'])y2=pd.Series(df3['ratio_YesNo'])subfig.add_bar( row=1, col=2,                x=x2,                y=y2)subfig.show()
All the code can be found in the Married.py file on Github here!
If you like my work, I’d greatly appreciate if you followed me Medium here.
If you have any questions, suggestions or ideas on how to improve, please leave a comment below or get in touch through LinkedIn here.