Opening the book…
By the end of this section, you should be able to:
- 9.5.1 Produce labeled scatterplots and scatterplots with variable density points, different colors, etc. to indicate additional information.
- 9.5.2 Create and interpret correlation heatmaps from multidimensional data.
- 9.5.3 Create and interpret graphs of three-dimensional data using a variety of methods.
A data scientist or researcher is often interested in generating more advanced visual representations such as scatterplots, correlation maps, and three-dimensional (3D) representations of data. Visualizations or graphs produced in a 3D format are especially important to convey a realistic view of the world around us. For example, on a manufacturing line, a 3D visualization of a mechanical component can be much easier to interpret than a two-dimensional blueprint drawing. 3D graphs can offer insights and perspectives that might be hidden or unavailable in a two-dimensional view.
3D visualizations are especially useful when mapping large datasets such as population density maps or global supply chain routes. In these situations, Python tools such as geopandas or 3D plotting routines available as part of matplotlib can be used to visualize relationships, patterns, and connections in large datasets.
As we saw in Decision-Making Using Machine Learning Basics, data collection and analysis of very large datasets, or big data, has become more common as businesses, government agencies, and other organizations collect huge volumes of data on a real-time basis. Some examples of big data include social media data, which generates very large datasets every second, including images, videos, posts, likes, shares, comments, etc. Data visualization for social media data might include dashboards to visualize trends and engagement on hot topics of the day (see more on these in Reporting Results), or geospatial maps to show the geographic distribution of users and associated demographics.
In this section, we explore more advanced visualization techniques such as scatterplots with variable density points, correlation heatmaps, and three-dimensional type analysis.
Scatterplots, Revisited
A scatterplot is a graphing method for bivariate data, which is paired data in which each value of one variable is paired with a value of a second variable, which plots x-variable, and the dependent, or response, quantity is labeled as the y-variable.
When generating scatterplots in Inferential Statistics and Regression Analysis, the plt.scatter() function was used, which is part of the Python matplotlib library. In Correlation and Linear Regression Analysis, an example scatterplot was generated to plot revenue vs. advertising spend for a company.
The Python code for that example is reproduced as follows:
Python Code
import matplotlib.pyplot as plt import matplotlib.ticker as ticker # Define the x-data, which is the amount spent on advertising x = [49, 145, 57, 153, 92, 83, 117, 142, 69, 106, 109, 121] # Define the y-data, which is revenue y = [12210, 17590, 13215, 19200, 14600, 14100, 17100, 18400, 14100, 15500, 16300, 17020] # Use the scatter function to generate a time series graph plt.scatter(x, y) # Add a title using the title function plt.title("Revenue versus Advertising for a Company") # Add labels to the x and y axes by using xlabel and ylabel functions plt.xlabel("Advertising $000") plt.ylabel("Revenue $000") # Define a function to format the ticks with commas as thousands separators def format_ticks(value, tick_number): return f'{value:,.0f}' # Apply the custom formatter to the y-axis plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(format_ticks)) # Show the plot plt.show()
The resulting output will look like this:
There are 50 records in the dataset (one record per state). The first five lines of the dataset appear in Table 9.6.
| total | speeding | alcohol | not_distracted | no_previous | ins_premium | ins_losses | abbrev |
|---|---|---|---|---|---|---|---|
| 18.8 | 7.332 | 5.64 | 18.048 | 15.04 | 784.55 | 145.08 | AL |
| 18.1 | 7.421 | 4.525 | 16.29 | 17.014 | 1053.48 | 133.93 | AK |
| 18.6 | 6.51 | 5.208 | 15.624 | 17.856 | 899.47 | 110.35 | AZ |
| 22.4 | 4.032 | 5.824 | 21.056 | 21.28 | 827.34 | 142.39 | AR |
| 12 | 4.2 | 3.36 | 10.92 | 10.68 | 878.41 | 165.63 | CA |
The short Python program that follows can be used to generate a correlation heatmap for the variables in the dataset; it makes use of the heatmap function available in the Seaborn library (see also Decision-Making Using Machine Learning Basics).
Python Code
import seaborn as sns import matplotlib.pyplot as plt # Load the car_crashes dataset from seaborn library dataset = sns.load_dataset("car_crashes") # Select only numeric columns numeric_columns = dataset.select_dtypes(include=['number']) # Calculate the correlation matrix correlation_matrix = numeric_columns.corr() # Generate the correlation heatmap using the Reds color palette sns.heatmap(correlation_matrix, cmap='Reds', annot=True, fmt=".2f") # Add a Title to the plot plt.title('Correlation Heatmap for Variables in Car Crashes Dataset') # Show the plot plt.show()
The resulting output will look like this:
We will use the mpl_toolkits.mplot3d() function to generate the three-dimensional scatterplot. First, we will read in the “iris” dataset from the Seaborn library. Next, the 3D scatterplot is created using the fig.add.subplot() function. The ax.scatter() function is then used to plot the data points.
Here is the Python code:
Python Code
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns import matplotlib.cm as cm import matplotlib.colors as mcolors from matplotlib.patches import Rectangle # Load the iris dataset from Seaborn data repository flower = sns.load_dataset('iris') # Create a blank figure with a white background fig = plt.figure(figsize=(9, 8), facecolor='white') # Add a subplot to the figure ax = fig.add_subplot(111, projection='3d') # Set the background color of the axes to white ax.set_facecolor('white') # Plot data points scatter = ax.scatter(flower['sepal_length'], flower['sepal_width'], flower['petal_length'], c=flower['species'].astype('category').cat.codes, cmap='viridis', marker='o') # Set labels and title ax.set_xlabel('Sepal Length (cm)') ax.set_ylabel('Sepal Width (cm)') ax.set_zlabel('Petal Length (cm)') ax.set_title('3D Scatterplot of Iris Dataset by Species') # Map numerical codes to actual species names species_names = {0: 'setosa', 1: 'versicolor', 2: 'virginica'} # Create a ScalarMappable object norm = plt.Normalize(flower['species'].astype('category').cat.codes.min(), flower['species'].astype('category').cat.codes.max()) sm = plt.cm.ScalarMappable(cmap='viridis', norm=norm) sm.set_array([]) # Create the colorbar and adjust its spacing cbar = plt.colorbar(sm, ticks=[0, 1, 2], label='Species', fraction=0.02, pad=0.1) # Adjust colorbar position to increase space between colorbar and plot cbar.ax.tick_params(labelsize=10) # Adjust the colorbar tick label size if needed # Adjust figure layout to provide appropriate space around the plot fig.subplots_adjust(left=0.1, right=0.85, top=0.9, bottom=0.1) # Adjust margins as needed # Add legend ax.legend(handles=scatter.legend_elements()[0], labels=[species_names[name] for name in flower['species'].astype('category').cat.codes.unique()], title='Species') plt.show()
The resulting output will look like this:
Datasets
Note: The primary datasets referenced in the chapter code may also be downloaded here.
This page titled 9.5: Multivariate and Network Data Visualization Using Python was last modified on Tue, 22 Apr 2025 14:34:58 GMT and is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.