Matplotlib vs. Plotly Express: Which One is the Best Library for Data Visualization? | by Ismael Araujo | Towards Data Science

Data visualization is one of the most critical steps of any project. Data visualizations have the power to translate complex information into an easy-to-digest chart. The more you use charts in your projects, the better you can present insights to non-technical individuals.
Whether you are a beginner or have years of experience using Python, you know that Matplotlib is the most famous data visualization, but is it the best one? Today we are going to compare Matplotlib to Plotly Express. Who is going to be the winner?
This is obvious, but Matplotlib is way more popular than Plotly. The main advantage of being so popular is that notebooks using Matplotlib will be easily reproduced by other people since different people’s chances of having it installed are higher. However, Plotly has been growing. Can it catch up with Matplotlib? In my opinion, if Matplotlib doesn’t make significant improvements in the next few years, I believe it will.
Plotly’s documentation is years ahead of Matplotlib. It’s easy to find information about the kind of plot that you are trying to create. Meanwhile, Matplotlib’s website is confusing. If you are a beginner, you will probably take a while to find what you are looking for.
Installing both libraries is equally easy. You can use pip or conda to install either one. There is not much to say here. One of the advantages of Python is how easy it is to install libraries. You should not have any problems installing any of them.
I know that you are here to see real-life comparisons between these two libraries, and that’s what we will do. To do so, I will use the World Happiness Report 2021 that you can find on Kaggle. You can find the notebook that I used to create these visualizations here.
# Importing Librariesimport opendatasets as odimport pandas as pdimport matplotlib.pyplot as pltimport plotly.express as pximport numpy as np# Setting the dataset to the variable dfdf = pd.read_csv('world-happiness-report-2021/world-happiness-report-2021.csv')
Let’s start with a bar chart, which is one of the most popular charts. Bar charts convey relational information quickly as the bars display the numbers related to a particular category, making it easy to compare elements inside the same category. For this chart, I will compare the happiness index by region. To do so, I will use the features Regional indicator and Ladder score.
I create a new data frame called happiest_regions to make things easier.
happiest_regions = df.groupby(by=[‘Regional indicator’])[‘Ladder score’].mean().sort_values(ascending=False).reset_index()happiest_regions = pd.DataFrame(happiest_regions)
Plotly Express
Plotly Express performed beautifully. It was able to deliver a beautiful interactive chart with very little code. Looking at the code, we can see that all we need to create a graph is the data frame, x-axis, y-axis, and I added color-coding to distinguish the regions better. Looks great to me!
px.bar(happiest_regions, x='Regional indicator', y='Ladder score', color='Regional indicator')
Matplotlib
Matplotlib result was... Hm, sad. I used about the same length of code as I used for Plotly, and the result looks terrible. It’s not possible to understand what is going on. That being said, it would require quite a bit of code to make this graph presentable. For this reason, I will have to cheat a little bit and include Seaborn into the game to make this comparison fair.
plt.bar(x = happiest_regions['Regional indicator'], height = happiest_regions['Ladder score'])plt.show()
Here we go. I tried to use the minimum code possible. I will say that the result is ok. It would need more lines of code to make it more professional, but it’s readable the way it is. Still, it’s a no for me.
# Importing Seabornimport seaborn as snssns.set_theme(style="darkgrid")plt.figure(figsize=(14,6))sns.barplot(x='Regional indicator', y='Ladder score', data=df, palette="tab10")plt.xticks(rotation=45, fontsize=14)plt.yticks(fontsize=14)plt.show()
Histograms’ primary objective is to see how the data is distributed and where the data is concentrated. For the histogram chart, I want to see how the happiness index is distributed. Thus, I will use the Ladder score feature.
Plotly
Again, Plotly did not disappoint. It’s able to show a nice interactive histogram with vert little code where we can color code the regions, which makes it very easy to get insights. For example, we can see where Western Europe and Sub-Saharan Africa is concentrated in the graph.
px.histogram(df, x='Ladder score', color='Regional indicator')
Matplotlib
Matplotlib was able to deliver a decent result. Yes, it requires more code, but we can easily recycle code from other charts. There is not much to talk about it. Compare to Plotly, it’s seems too simple. It is not interactive, but it gets the job done.
plt.figure(figsize=(14,6))sns.histplot(data=df, x='Ladder score', hue='Regional indicator')plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
Scatterplots are used to see if there is a correlation between two categories. It’s an essential step in machine learning and analyzes how a feature might affect another.
Plotly Express
We are in the third chart, and we can see that Plotly Express performs consistently well with different kinds of graphs. Transitioning from one type to another is very easy, and I didn’t have to deal with any errors while testing it. It’s easy to understand the code and what you need to change. Their website is clear, and you can easily find information about graphs. I love the interaction and that we can select what data you can see.
px.scatter(df, x='Ladder score', y='Logged GDP per capita', color='Regional indicator')
Matplotlib
Matplotlib is not super behind. It gets the job done, and once you have the code, you can transition between types of graphs just as easily as Plotly Express. No, it’s not interactive (without additional libraries). Yes, it does the work that you would expect from a scatter plot.
plt.figure(figsize=(14,6))sns.scatterplot(data=df, x='Ladder score', y='Logged GDP per capita', hue='Regional indicator')plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
Line charts are handy to see the trend of a specific category. For example, we can see how the Ladder score changed over the years. Are countries becoming happier? It's a fundamental chart to understand how the progress of your category looks like. For the line charts, I will use the World Happiness report over the years.
Plotly Express
At this point, we can expect that Plotly Express will perform well, right? Yes, it delivers a beautiful chart, but I want to focus on two exciting functionalities. The first one is that you can scroll and see all the countries. It’s still an excellent functionality. The other cool thing is that if you start unchecking multiple, in this case, countries, Plotly is smart enough to uncheck all countries. A nice detail.
px.line(df2, x='year', y='Life Ladder', color='Country name')
Matplotlib
Matplotlib did a good job with line plots. It has two ways of seeing it. The first one is not including the color code. Matplotlib will create what seems to be a trend, including all the countries. Could that be the mean values? This is what Matplotlib’s documentation says about the line plot.
Draw a line plot with possibility of several semantic groupings.
It’s not clear what we should expect. Anyway, the graph looks good. If it shows a worldwide trend, we can see a significant drop in the Ladder index in 2006. There was a recession that year that got aggravated in 2008. Maybe that is the reason why we see this trend.
plt.figure(figsize=(14,6))sns.lineplot(data=df2, x='year', y='Life Ladder')plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
However, we can color code the lines and see individual lines for each code. It does the job. Again, it’s interactive, but it works, and it looks... hmm, ok.
plt.figure(figsize=(14,6))sns.lineplot(data=first_10_countries, x='year', y='Life Ladder', hue='Country name')plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
You have probably noticed that none of the graphs have a title, and they need some work to look more professional. Matplotlib delivers horrible results if we don’t make some adjustments. Luckily, we have Seaborn that makes the initial results way better. You can get the insights you need from the dataset, but they are not presentable for a professional environment. The good news is that you can intercalate the code you would use with Seaborn and Matplotlib. In the examples I used here in this blog, I used Seaborn to create the charts and Matplotlib to make some adjustments.
I think that Matplotlib’s documentation is not good. It’s confusing, and it’s hard to find what you need. However, editing the plots is straightforward, and the code is easy to remember. This blog written by Preeya Sawadmanod does a fantastic job explaining how you can create and edit your Matplotlib plots.
Above, we can see that we can improve the chart by adding a few more lines of code. Beginners should not have problems editing Matplotlib’s graphs
plt.figure(figsize=(14,6))sns.lineplot(data=first_10_countries, x='year', y='Life Ladder', hue='Country name')plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
On the other hand, Plotly delivers ready-to-present data visualizations. Its charts are beautiful and require minimal styling to look professional. It’s interactive, so you can edit the selection of categories live! It’s also possible to edit the font you are using, color, and animate the charts. It wins against Matplotlib and Seaborn by a lot.
plt.figure(figsize=(14,6))sns.histplot(data=df, x='Ladder score', hue='Regional indicator', palette='husl')plt.title('Ladder Score Distribution', fontsize=18)plt.xlabel('Ladder Score', fontsize=16)plt.ylabel('Count', fontsize=16)plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
There is so much to consider when analyzing these two excellent libraries. However, the objective of this blog was to decide which one is the winner, and I do not doubt that Plotly Express deserves this title of best data visualization library when compared to Matplotlib. It doesn’t mean that Matplotlib is terrible, it just requires more code, and it lacks additional functionalities. Meanwhile, Plotly Express delivered beautiful results with very little code. It’s easy to use and remember the code to create a chart.
If you are a beginner, you should learn Matplotlib and Seaborn because they are more popular. However, when you are ready, Plotly Express should be the next on your list. If you an advanced Python user, you should try Plotly Express and all its advanced functionalities.
Thanks for reading. Let me know your opinion about these two libraries.
If you have any questions, reach me out on my Linkedin: http://bit.ly/linkedin-ismael