Top Python Libraries for Visualization: A Starting Guide | by Michael Zabolocki | Towards Data Science

Given the enormous number of libraries and possibilities for data visualization in Python, it can quickly become a difficult and somewhat overwhelming endeavour to navigate through for anyone new to the field. There is an abundance of options to choose from, but knowing which is correct for you (and why) is an important step to effectively showcasing data. In this article we focus on several key libraries for effective data visualization, and provide clear working examples for implementation into any dataset.
In lay terms, data visualization is the ‘art’ of utilising graphic displays to show raw data. More specifically, it is useful for exploring data structure, detecting outliers, trends, and clusters to reduce data complexity. Hence, effective data visualization will help convey data to a target audience in an easily understandable visual context for the human brain.
The landscape of data visualization is here to stay and continues to evolve with technological advances, leaving a more-and-more prominent footprint in scientific publications, media and website displays. More precise reproduction, better color (including alpha-blending), and even faster plotting are some variables which have rapidly improved within the last decade.
Furthermore, progress has also been made in developing graphic theories, such as Wilkinson’s Grammar of Graphics (2005) and Hadley Wickham’s implementation of it in the R package ggplot2 (Wickham, 2016). In doing so, graphics that were rarely used in the past and difficult to draw, such as parallel coordinate plots (e.g., Theus, 2015) and mosaicplots (e.g., Unwin, 2015), have now been refined and developed.
Many no-code tools for data visualization exist such as Tableau, Power BI, ChartBlocks, Prism, and more. However, even though programming is required, Python is one of the preferred languages among data scientists due to its visualization capabilities. This is also accompanied by data collection and exploration libraries (e.g. Pandas, NumPy, SciPy) for data manipulation and transformation. Already, Python has numerous libraries and features available for visualization which will continue to grow due to its large user base and open source nature. With the ever evolving technological landscape, Python is in excellent stead to maintain its position as the preferred language amongst data scientists for years to come.
There are numerous ways to plot statistical graphics with Python, however some of my preferred can be created with the following libraries listed below. In this article we will focus on plotting heatmaps, scatter plots, line graphs and ridgeline plots using the following:
joypy
seaborn
plotly.express
For general interest, I have summarised key library information with links to source documentation:
Plotly Express is a high-level Python visualization library, serving as a wrapper for Plotly.py that exposes a simple syntax for complex charts. It can be used to make richly interactive plots in just a single function call, including faceting, maps, animations, and trendlines. Plotly Express is also fully compatible with the rest of the Plotly ecosystem.
Seaborn builds ontop of matplotlib, and works by capturing entire dataframes or arrays containing data and performs necessary internal functions for semantic mapping and statistical aggregation to produce informative plots.
Joypy is a one-function Python package based on matplotlib and pandas with a single purpose: drawing joyplots (i.e. ridgeline plots). This library is very useful for visualizing data distributions in a clear manner.
If not already, please install these libraries via the terminal by running the following command line(s):
pip install seabornpip install joypypip install plotly
Once complete, we will import the following nodules before continuing:
import numpy as npimport pandas as pdimport seaborn as snsfrom joypy import joyplotimport plotly.express as pxfrom scipy import statsimport matplotlib.pyplot as plt
Without data, we can not visualize anything. So before we step through a series of plotting examples, we will load the following in-built (and commonly used) python dataset about flights using the seaborn library:
# Load a dataframeflights_data = sns.load_dataset("flights")# Display datasetflights_data.head()
Basic scatter plots can be made using plotly.express, with the flexibility to alter their width and height for more optimal image exports. Templates can also be changed from simple_white to incorporate grids and darker color:
px.scatter(flights_data, x=”year”, y=”passengers”, width=700, height=600,template=”simple_white”)
Notably, plotly.express is great for colour sequencing, which is why I prefer it for visualizing grouped data. You also have the option to change colors from a discrete color sequence (shown below) to a continuous color scheme, which serves effective for continuous data measurements. Overall, different colours can be given to different data groups for improved visual clarity.
#group data flights_data.loc[flights_data.year <= 1954 , 'group'] = '<= 1954'flights_data.loc[flights_data.year > 1954 , 'group'] = '> 1954' #re-plot data with discrete color schemepx.scatter(flights_data, x="year", y="passengers", width=700, height=600, template="simple_white", color="group", color_discrete_sequence=['red','blue'])
If you are like me and despise the default aesthetics on the scatter plots, here are some helpful examples which can be implemented to change tick lengths, font sizes, axis titles, marker colors, and more:
#size dimension changefig1 = px.scatter(flights_data, x="year", y="passengers", width=700, height=450,template="simple_white", color="group",color_discrete_sequence=['red','blue'])#tick font and size changefig1.update_layout(yaxis = dict(tickfont = dict(size=20)),xaxis = dict(tickfont = dict(size=20)),font_family="Arial")#x-axis title and size + tick length changesfig1.update_xaxes(title_text = "Year of flight",title_font = {"size": 20},title_standoff = 15, ticklen=10)#y-axis title and size + tick length and value changesfig1.update_yaxes(title_text = "Passengers",title_font = {"size": 20},title_standoff = 15, ticklen=10, tickvals=list(range(0,700,100)))#marker size, outline and color change fig1.update_traces(marker=dict(size = 9,line=dict(width=0.8, color='white')),selector=dict(mode='markers'))#legend off fig1.update_layout(showlegend=False)    fig1.show()
Notably, you can choose any of the following built-in qualitative color sequences from the px.colors.qualitative module, or define your own:
Even though plotly.express has the option to add a trendline, here we show how to implement a filled trendline to the existing data using seaborn libraries. This is particularly helpful to visualize relationships between variables. In the case of year and passenger variables, a linear relationship can be seen and hence a trendline will help to reinforce this.
#use lmplot to plot scatter pointssns.set(font_scale = 1.6)sns.set_style("white")fig2 = sns.lmplot(data = flights_data, x="year", y="passengers", height=5, aspect=1.64, legend=False, line_kws={'color': 'black'}, scatter_kws={"color": "black"})#change axis titlesfig2.set(xlabel='Year of flight', ylabel='Passengers')
To maintain the color scheme for previous data groups we can specify color to specific datapoints. A filled trendline can also be applied to the entire data set, as shown below:
#get coeffs of linear fitslope, intercept, r_value, p_value, std_err = stats.linregress(flights_data['year'],flights_data['passengers'])#use lmplot to plot scatter pointssns.set(font_scale = 1.6)sns.set_style("white")sns.lmplot(data = flights_data, x="year", y="passengers", height=5, aspect=1.64, hue="group", fit_reg= False, legend=False, palette=["red","blue"])#use regplot to plot the regression line and use line_kws to set line label for legendfig3 = sns.regplot(data = flights_data, x="year", y="passengers", scatter_kws={"zorder":-1}, line_kws={'label':"y={0:.1f}x+{1:.1f}".format(slope,intercept)}, color="black")#change axis titlesfig3.set(xlabel='Year of flight', ylabel='Passengers')
Alternatively, a separate filled trendline can be applied to each group using the following code:
#use lmplot to plot scatter pointssns.set(font_scale = 1.6)sns.set_style("white")fig4 = sns.lmplot(data = flights_data, x="year", y="passengers", height=5, aspect=1.64, hue="group", palette=["red","blue"], legend = False)#change axis titlesfig4.set(xlabel='Year of flight', ylabel='Passengers')
In all cases, to simplify the data the mean (or median) of all y-values for each corresponding x-value can be displayed as shown below:
#set fontsizesns.set(font_scale = 1.6)sns.set_style("white")fig5 = sns.regplot(data = flights_data, x="year", y="passengers", x_estimator=np.mean, color = "black")#set fig sizefig5.figure.set_size_inches(8.2, 4.5)#change axis titlesfig5.set(xlabel='Year of flight', ylabel='Passengers') #despinesns.despine()
It is easy to see looking at the line and scatter plots that data distribution within each group is significantly varied. Joyplots or ridgeline plots in Python can be an excellent method to visualizing said distribution while providing insight into distribution types (e.g. normal, gamma, beta). For a refresher, an excellent summary of these can be found here.
One library I particularly enjoy to visualize joyplots or ridgeline plots in Python is — joypy. It boils down to a single function call, making it easy to use and alter.
# x variables to plot with corresponding textxvar = ['year', 'passengers']xlabel = ['Year of flight', 'Passengers']for x,xlabel in zip(xvar,xlabel):    joyplot(data = flights_data[[x, "group"]],             by="group", figsize=(10, 4),             labels = ["Group 1","Group 2"],            linecolor = 'black',            color = ['red','blue'],             alpha = 0.85,             linewidth=3, overlap = 0.9)    plt.rc("font", size=24)    plt.xlabel(xlabel, fontsize = 24)    plt.show()
Of course, this is a simplified ridge-line plot for the two arbitrary groups and the amount you can do with this library is up to the user. Additional documentation can be found here with further examples for inspiration.
Heatmaps can provide a simplified summary of your dataset with a color coded overlay. To achieve this, the seaborn library provides a variety of options for heatmap plotting.
For this example, I have grouped the dataset by “year” and produced both mean and median outputs into one concatenated dataframe. This enabled me to simplify the dataset before heatmap generation:
#grouped flights_data and calculated meangrouped_df = flights_data.groupby("year")mean_df = grouped_df.mean()mean_df.rename({'passengers': 'Mean'}, axis=1, inplace=True)mean_df = mean_df.reset_index()#grouped flights_data and calculated medianmedian_df = grouped_df.median()median_df.rename({'passengers': 'Median'}, axis=1, inplace=True)median_df = median_df.reset_index()#concat dataframesdata_concat = pd.concat([median_df['Median'], mean_df['Mean']], axis=1, ignore_index=False)#display data_concat.head()
Once complete, you can plot your heatmap for each year:
#finding y-axis titlesy_axis_labels = flights_data.year.unique()# plot heatmapfig, ax = plt.subplots(figsize=(6,10)) fig7 = sns.heatmap(data_concat, cmap="vlag", linewidth=0.1, annot=data_concat, fmt=".2f", cbar_kws={'label': 'Passengers', "shrink": .4}, annot_kws={"size": 16}, yticklabels=y_axis_labels)# set yticks and axis labelplt.yticks(rotation=0) fig7.set(ylabel='Year of flight')
Of course, the field of data science has a large variety of tools available for data visualization which are endlessly improving and changing. However, keeping up to date and navigating this for anyone new to the Python language can be a somewhat overwhelming task.
To summarize — key libraries such as seaborn joypy and plotly.expressoffer an effective starting point for anyone new to data visualization with Python. In this article we utilized these to generate scatter plots, heat maps, line graphs and joy plots with a simple dataset.
I hope that you enjoyed reading this article as much as I enjoyed writing it.
In upcoming articles I will being to dive into machine-learning and deep-learning theory, along with further data visualization techniques.