Creating 3D heatmap with CSV file
- We are using pandas we have loaded the dataset and we are using 3 columns for plotting and one column for color bar. You can operate the data as your wish.
- Using plt.figure, we have created a figure of size 8×5 width and height respectively by default the matplotlib will produce 2D plots, so to specify this as a 3d plot we use add_subplot function with projection=’3d’ to create a 3d plot. We are mapping an array of integers as an RGBA color for our plot using the set_array() function.
- After that, we are creating a scatter plot with our 3d dataset and by setting marker value as s we are displaying each data point as square-shaped. Their color will depend on the array that we have created earlier called colo.
- At last, we have set the x, y, z labels and title using the set_label function and displayed the plot using show() function.
Download the dataset from here.
Python3
#!/usr/bin/python3 # 3D Heatmap in Python using matplotlib # to make plot interactive % matplotlib inline # importing required libraries from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import pandas as pd from pylab import * # reading a dummy dataset dataset = pd.read_csv( "/data.csv" ) x = dataset[ "Col.1" ].tolist() y = dataset[ "Col.2" ].tolist() z = dataset[ "Col.3" ].tolist() colo = dataset[ "total" ].tolist() # creating 3d figures fig = plt.figure(figsize = ( 8 , 5 )) ax = fig.add_subplot( 111 , projection = '3d' ) # configuring colorbar color_map = cm.ScalarMappable(cmap = cm.gray) color_map.set_array(colo) # creating the heatmap img = ax.scatter(x, y, z, marker = 's' , s = 99 , color = 'gray' ) plt.colorbar(color_map) # adding title and labels ax.set_title( "3D Heatmap" ) ax.set_xlabel( 'X' ) ax.set_ylabel( 'Y' ) ax.set_zlabel('') # displaying plot plt.show() |
Output:
3D Heatmap in Python
Heatmaps are a great way to visualize a dataset, methods for visualizing the data are getting explored constantly and 3D heatmap is one of the ways to plot data. Let’s learn how we can plot 3D data in python. We are going to use matplotlib and mplot3d to plot the 3D Heatmap in Python. We need to install the matplotlib explicitly by running the following command in the console:
pip3 install matplotlib
Contact Us