Plotly VS matplotlib: What is the best library for data visualization in Python?
By: Angelica Lo Duca
Tags: Data Visualization, Graph, Plotly, Matplotlib, Python

Image by Goumbik from Pixabay

In this short tutorial, I show you how to quickly build a basic line chart using the plotly and matplotlib libraries. Referring to plotly , I will use the Graph Objects, which are plotly classes used to represent parts of a figure. For details regarding the Graph Objects, you can refer to the official plotly documentation.

You can download the code of this tutorial from my Github repository.

Import Data

Firstly, I import data into a pandas dataframe. I use the read_csv() function. The dataset contains the number of tourist presences in Italian accommodation, divided per town or total.

import pandas as pd df = pd.read_csv('presenza_negli_alberghi.csv')

df

Image by Author

Data Filtering

You can skip this section if you are in a hurry to draw the graph :).

Since I want to plot the total number of presences, I must apply some filters. I convert the Sigla column to a string, in order to perform some comparisons and then I maintain only rows having the length of the value in the column Sigla greater than 2.

import numpy as np

df['Sigla'] = df['Sigla'].astype('str')

regions = df['Sigla'].apply(lambda x: x if len(x) > 2 else np.nan).dropna().unique()

Now I filter data in order to maintain only the total number of data.

df_it = df[(df['Territorio'] == 'Italia') & (df['Esercizio'] == 'totale esercizi ricettivi') & (df['Indicatori'] == 'presenze')]

df_it

Image by Author

Matplotlib

Now I exploit the matplotlib library to plot the basic line. I can set the figura size through the figure() function. This function must be called before the call to the other functions. I call the plot() function, by passing the x and y as the first two parameters, as well as the line color parameter (orange), the linewidth (2), and the value of the alpha parameter (0.7) to set the plot transparency. I also define the style to be used through the style.use() function. Then I specify the plot title (function title() and xlabel() and ylabel() . Finally, I invoke the show() function to draw the graph.

import matplotlib.pyplot as plt

plt.figure(figsize=(15,7))

plt.plot(df_it['Periodo'], df_it['Dato'], marker='', color='orange', linewidth=2, alpha=0.7)

plt.style.use('seaborn')

plt.title("Number of presences in the Italian Accommodations", loc='right', fontsize=12, fontweight=0)

plt.xlabel("Year")

plt.ylabel("Number of Presences") plt.show()

Image by Author

Plotly

The same graph can be plotted through the plotly library. After importing plotly.graph_objects , I define a Figure() to which we pass two parameters: data and mode . Mode contains the type of line (in my case lines+markers ) while data contains a Scatter() object. Within the Scatter() object, I must specify the x and the y as well as the line options (color, width). Then I call the update_layout() function to define the plot options, such as the title and the y and x labels. Finally, I plot the graph through the show() function.

import plotly.graph_objects as go

import numpy as np fig = go.Figure(data=go.Scatter(x=df_it['Periodo'], y=df_it['Dato'],line=dict(color='orange', width=2),mode='lines+markers'))

fig.update_layout(

title={

'text': "Number of presences in the Italian Accommodations",

'y':0.9,

'x':0.5,

'xanchor': 'center',

'yanchor': 'top'},

xaxis_title="Year",

yaxis_title="Number of presences"



)

fig.show()

Image by Author

Discussion & Summary

The two analyzed libraries produce a similar result. However, their approach is quite different, because matplotlib defines a function for each operation to be performed, such as title() , xlabel() and ylabel() , while plotly defines a layout, which receives a dictionary as input. Which one is the best? There is not the best library. It depends on your sensitivity. Personally, I prefer matplotlib but you are free to use what you want.

Indeed, other libraries exist for data visualization in Python, such as Vega Lite. If you want to learn something about this library, please stay tuned…

If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube, and Github.