If I understand you correctly you have three columns with X and Y denoting the position of a value Z.

Consider the following example. There are three columns: X and Y contain positional information (categories in this case) and Z contains the values for shading the heatmap.

x = np.array(['a','b','c','a','b','c','a','b','c'])
y = np.array(['a','a','a','b','b','b','c','c','c'])
z = np.array([0.3,-0.3,1,0.5,-0.25,-1,0.25,-0.23,0.25])

Then we create a dataframe from these columns and transpose them (so x,y and z actually become columns). Give column names and make sure Z_value is a number.

df = pd.DataFrame.from_dict(np.array([x,y,z]).T)
df.columns = ['X_value','Y_value','Z_value']
df['Z_value'] = pd.to_numeric(df['Z_value'])

resulting in this dataframe.

X_value Y_value Z_value
0   a   a   0.30
1   b   a   -0.30
2   c   a   1.00
3   a   b   0.50
4   b   b   -0.25
5   c   b   -1.00
6   a   c   0.25
7   b   c   -0.23
8   c   c   0.25

From this you cannot create a heatmap, however by calling df.pivot('Y_value','X_value','Z_value') you pivot the dataframe to a form that can be used for a heatmap.

pivotted= df.pivot('Y_value','X_value','Z_value')

The resulting dataframe looks like this.

X_value a   b   c
Y_value         
a   0.30    -0.30   1.00
b   0.50    -0.25   -1.00
c   0.25    -0.23   0.25

You can then feed pivotted to the sns.heatmap to create your heatmap.

sns.heatmap(pivotted,cmap='RdBu')

Resulting in this heatmap.

You may need to make some adjustments to the code for your precise needs. But since I had no example data to go from I needed to make my own example.

Answer from error on Stack Overflow
🌐
CodersLegacy
coderslegacy.com › home › python › plotting a 2d heatmap with matplotlib in python
Plotting a 2D Heatmap With Matplotlib in Python - CodersLegacy
July 15, 2022 - The min and max values that we are using are not the literal min and max values from the Z-dataset. Rather, we are using the value with largest magnitude. Our goal is to ensure that the heatmap is uniform (which it might not be if we use the literal values). You can try it both ways, and see the difference for yourself. (You may end up needing the other technique depending on your data, so you should understand both) Here is the final code. import matplotlib.pyplot as plt import numpy as np x, y = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100)) z = (1 - x*y) - np.sin(x**2 + y**2 ) z = z[:-1, :-1] fig, ax = plt.subplots() ax.set_title('Heatmap with Colormesh') plt.pcolormesh(x, y, z, cmap='RdBu', vmin = -np.abs(z).max(), vmax = np.abs(z).max()) plt.colorbar() plt.show()
🌐
Rip Tutorial
riptutorial.com › heatmap
matplotlib Tutorial => Heatmap
from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib import matplotlib.pyplot as plt # Define numbers of generated data points and bins per axis. N_numbers = 100000 N_bins = 20 # set random seed np.random.seed(0) # Generate 2D normally distributed numbers. x, y = np.random.multivariate_normal( mean=[0.0, 0.0], # mean cov=[[1.0, 0.4], [0.4, 0.25]], # covariance matrix size=N_numbers ).T # transpose to get columns fig = plt.figure() ax = fig.add_subplot(111, projection='3d') hist, xedges, yedges = np.histogram2d(x, y, bins=N_bins) # Add title and labels to plot.
Top answer
1 of 1
15

If I understand you correctly you have three columns with X and Y denoting the position of a value Z.

Consider the following example. There are three columns: X and Y contain positional information (categories in this case) and Z contains the values for shading the heatmap.

x = np.array(['a','b','c','a','b','c','a','b','c'])
y = np.array(['a','a','a','b','b','b','c','c','c'])
z = np.array([0.3,-0.3,1,0.5,-0.25,-1,0.25,-0.23,0.25])

Then we create a dataframe from these columns and transpose them (so x,y and z actually become columns). Give column names and make sure Z_value is a number.

df = pd.DataFrame.from_dict(np.array([x,y,z]).T)
df.columns = ['X_value','Y_value','Z_value']
df['Z_value'] = pd.to_numeric(df['Z_value'])

resulting in this dataframe.

X_value Y_value Z_value
0   a   a   0.30
1   b   a   -0.30
2   c   a   1.00
3   a   b   0.50
4   b   b   -0.25
5   c   b   -1.00
6   a   c   0.25
7   b   c   -0.23
8   c   c   0.25

From this you cannot create a heatmap, however by calling df.pivot('Y_value','X_value','Z_value') you pivot the dataframe to a form that can be used for a heatmap.

pivotted= df.pivot('Y_value','X_value','Z_value')

The resulting dataframe looks like this.

X_value a   b   c
Y_value         
a   0.30    -0.30   1.00
b   0.50    -0.25   -1.00
c   0.25    -0.23   0.25

You can then feed pivotted to the sns.heatmap to create your heatmap.

sns.heatmap(pivotted,cmap='RdBu')

Resulting in this heatmap.

You may need to make some adjustments to the code for your precise needs. But since I had no example data to go from I needed to make my own example.

🌐
Matplotlib
matplotlib.org › stable › gallery › images_contours_and_fields › image_annotated_heatmap.html
Annotated heatmap — Matplotlib 3.11.2 documentation
**kwargs All other arguments are forwarded to `imshow`. """ if ax is None: ax = plt.gca() if cbar_kw is None: cbar_kw = {} # Plot the heatmap im = ax.imshow(data, **kwargs) # Create colorbar cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw) cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom") # Show all ticks and label them with the respective list entries. ax.set_xticks(range(data.shape[1]), labels=col_labels, rotation=-30, rotation_mode="xtick") ax.set_yticks(range(data.shape[0]), labels=row_labels) # Let the horizontal axes labeling appear on top.
🌐
Wordpress
syeilendrapramuditya.wordpress.com › 2023 › 01 › 04 › heatmap-plot-of-xyz-data-from-file-with-python-numpy-matplotlib-2d-colored-heatmap
Heatmap Plot of XYZ data from file with Python / Numpy / Matplotlib (2D Colored Heatmap) – Hey, what's going on?
January 6, 2023 - / Python Programming Basics / Syeilendra Generate a heatmap from xyz data file Tested with Spyder 3.9 ''' from datetime import datetime import numpy as np import matplotlib.pyplot as plt # ***** Main Program - Begin ***** now = datetime.now() localtime = now.strftime("%a %d-%m-%Y %H:%M:%S") print("2D Colored Heatmap") # Read data from text file array_txt = np.loadtxt("datafile1.txt",usecols=(2,3,4)) #array_txt = np.loadtxt("datafile2.txt",usecols=(2,3,4)) x = array_txt[:,0] y = array_txt[:,1] z = array_txt[:,2] x=np.unique(x) y=np.unique(y) X,Y = np.meshgrid(x,y) Z=z.reshape(len(x),len(y)) Z=n
Top answer
1 of 3
1

My answer is a small edit to answer provided by warped.

The difference is the inclusion of the parameter 'extend' in the contourf method call.

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contourf.html

For some more information about the minimum/maximum color-map behaviour, see:

https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/contourf_demo.html#sphx-glr-gallery-images-contours-and-fields-contourf-demo-py

# libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import kde
from scipy.interpolate import griddata

# Get the data (csv file is hosted on the web)
url = 'https://raw.githubusercontent.com/ampil/sandbox/master/latest-sales-sample.csv'
df = pd.read_csv(url, sep = ';')
df = df.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
# create data
x = df['X']
y = np.log(df['Y'])
z = df['cluster']

#following 2 lines provided by user-warped
xi = np.arange(0, np.max(x), 0.1)
yi = np.arange(0, np.max(y), 0.1)

xi, yi = np.meshgrid(xi,yi)

# interpolate
zi = griddata((x,y),z,(xi,yi),method='cubic')

#define color map...which you can choose to modify with 'set_under' and 'set_over'
#as per: https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/contourf_demo.html#sphx-glr-gallery-images-contours-and-fields-contourf-demo-py
cmap = plt.cm.get_cmap("coolwarm")

fig = plt.figure()
ax = fig.add_subplot(111)
ax.axis((x.min(), x.max(), y.min(), y.max()))

#added the 'extend' parameter to user:warped edit as per documentation of plt.contourf
#https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contourf.html
plt.contourf(xi, yi, zi, levels=[1,2,3,4,5,6], cmap=cmap, extend='both')
plt.plot(x, y,'k.')

plt.xlabel('x',fontsize=16)
plt.ylabel('y',fontsize=16)
plt.show()

As far as extending the colours beyond what they are now...you'd get a result that would look very different from the main area and would likely have little meaning. If this were a GIS application, I would have those exterior pixels to be "NODATA".

EDIT: Providing evidence that filling the exterior would look strange...

Using a canned gdal method to fill nodatas, this is what it would look like:

This was quick and dirty and other methods likely exist but would probably look equally odd. Perhaps numpy.nan_to_num is another solution if you don't have gdal.

In case you're curious...here's the code (continues from previous code block):

import gdal
ds = gdal.GetDriverByName('MEM').Create('', zi.shape[1], zi.shape[0], 1, gdal.GDT_Float32)
in_band = ds.GetRasterBand(1)
in_band.SetNoDataValue(-9999)
in_band.FlushCache()

raster_data = np.copy(zi)
raster_data[np.isnan(zi)] = -9999

in_band.WriteArray(raster_data)

#this line takes a while to run...grab a coffee
result = gdal.FillNodata(in_band, None, maxSearchDist=20000, smoothingIterations=0)
in_band.FlushCache()

newz = in_band.ReadAsArray()

fig = plt.figure()
ax = fig.add_subplot(111)
ax.axis((x.min(), x.max(), y.min(), y.max()))

#added the 'extend' parameter as per documentation of plt.contourf
#https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.contourf.html
plt.contourf(xi, yi, newz, levels=[1,2,3,4,5,6], cmap=cmap, extend='both')
plt.plot(x, y,'k.')

plt.xlabel('x',fontsize=16)
plt.ylabel('y',fontsize=16)
plt.show()
2 of 3
1
import matplotlib
colors = ['red','green','blue','purple','black', 'coral']

fig = plt.figure(figsize=(8,8))
plt.scatter(x, y, c = z, cmap=matplotlib.colors.ListedColormap(colors))
plt.show()

Find elsewhere
🌐
TECH CHAMPION
tech-champion.com › tech champion › data science › heatmap data visualization: plotting x y and z arrays
Heatmap Data Visualization: Plotting x y and z Arrays
January 28, 2025 - import numpy as np import matplotlib.pyplot as plt # Sample data (replace with your actual data) x = np.linspace(0, 10, 81) y = np.linspace(0, 10, 81) X, Y = np.meshgrid(x, y) z = np.sin(X) * np.cos(Y) plt.imshow(z, extent=[x.min(), x.max(), y.min(), y.max()], origin='lower', cmap='viridis') plt.colorbar(label='Z Value') plt.xlabel('X') plt.ylabel('Y') plt.title('Heatmap of Z') plt.show()
🌐
Readthedocs
xyzpy.readthedocs.io › en › latest › plotting.html
Plotting - xyzpy 1.3.6.dev34+g05703cf48 documentation
This can be very useful if plotting ... you can then use to annotate each point with the xlink dimension value. Heatmaps can be draw by specifying a z data variable in addition to x and y coordinates....
🌐
Python-Fiddle
python-fiddle.com › tutorials › matplotlib-heatmap
Creating and Customizing Heatmaps in Matplotlib
- **`pcolormesh(X, Y, Z, shading='auto', cmap='coolwarm')`** creates the heatmap using `X` and `Y` as grid coordinates and `Z` as the data values. ### Creating Heatmaps with `matshow` Another convenient method for creating heatmaps is using the `matshow` function, which is a specialized version ...
🌐
GeeksforGeeks
geeksforgeeks.org › 3d-heatmap-in-python
3D Heatmap in Python | GeeksforGeeks
July 28, 2021 - At last, we have set the x, y, z labels and title using the set_label function and displayed the plot using show() function. ... # 3D Heatmap in Python using matplotlib # to make plot interactive %matplotlib # importing required libraries from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from pylab import * # creating a dummy dataset x = np.random.randint(low=100, high=500, size=(1000,)) y = np.random.randint(low=300, high=500, size=(1000,)) z = np.random.randint(low=200, high=500, size=(1000,)) colo = [x + y + z] # creating figures fig = plt.figure(fig
🌐
Plotly
plotly.com › python › heatmaps
Heatmaps in Python
... import plotly.express as px ... text_auto=True, aspect="auto") fig.show() You can use the x, y and labels arguments to customize the display of a heatmap, and use .update_xaxes() to move the x axis tick labels to ...
🌐
Seaborn
seaborn.pydata.org › generated › seaborn.heatmap.html
seaborn.heatmap — seaborn 0.13.2 documentation - PyData |
Use methods on the matplotlib.axes.Axes object to tweak the plot: ax = sns.heatmap(glue, annot=True) ax.set(xlabel="", ylabel="") ax.xaxis.tick_top()
🌐
YouTube
youtube.com › codemake
Make a heatmap of x y z data in Python - YouTube
Download this code from https://codegive.com Certainly! Creating a heatmap of x, y, z data in Python can be achieved using libraries like Matplotlib and NumP...
Published: November 26, 2023
Views: 116