0

I have a 2d matrix of values which I would like to plot as a 2d histogram.

A simplified example: I have a 1d array of initial velocities, say vi = [1, 2, 3], and for each value in vi, I have a row of corresponding final velocities stored in a 2d array, vf = [ [0.7, 1.1, 1.5], [1.8, 2.1, 2.4], [2.7, 2.9, 3.1] ]. I want to be able to make a 2d histogram of the points (vi, vf), i.e., the coordinates [1, 0.7], [1, 1.1], [1, 1.5], [2, 1.8], [2, 2.1], [2, 2.4], and [3,2.7], [3, 2.9], [3, 3.1].

Is there a way to create such parings?

The answer to this question advises to use imshow or matshow, but that colors bins by the value assigned to each element. What I need is a plotting routine that takes a 2d matrix, divides it into a grid, and colors each bin by the count in each bin.

Any help is appreciated!

2
  • You should at least add an example of your data and explain how you want them in 2d bins. Where do the values stand for? Commented Feb 8, 2021 at 15:34
  • added an example Commented Feb 9, 2021 at 19:16

1 Answer 1

1

You seem to have a 2D space, where the x-values come from vi and the y-values from vf. Repeating vi n times (with n the row-length of vf) makes the x and y arrays have the same number of elements, corresponding to the desired tuples.

In code:

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

vi = np.array([1, 2, 3])
vf = np.array([[0.7, 1.1, 1.5], [1.8, 2.1, 2.4], [2.7, 2.9, 3.1]])

x = np.repeat(vi, vf.shape[1]) # repeat the x-values by the row-length of `vf`
y = vf.ravel() # convert to a 1D array
sns.histplot(x=x, y=y)
plt.show()

With so little data, the plot looks quite uninteresting. You'll have to test with the real data to find out whether it is what you're expecting.

print([*zip(x,y)]) prints (x,y) as tuples, i.e.

[(1, 0.7), (1, 1.1), (1, 1.5), (2, 1.8), (2, 2.1), (2, 2.4), (3, 2.7), (3, 2.9), (3, 3.1)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.