insomnia
insomnia

Reputation: 301

How to plot this figure?

enter image description here

I'd like to plot something like above plot using python. There is one feature I like:

The figure is divided into several rectangles with different color (and number). the only approximate plot I can think is scatter plot. But a scatter plot present some points, not rectangles.

Can anyone help me?

Upvotes: 1

Views: 54

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339705

The answer probably depends on what kind of data you want to show. There are several ways to produce such a plot,

  1. Using Rectangles with given vertices
  2. Using imshow of an array on an equally spaced grid
  3. Using pcolormesh of an array on an unequally spaced grid

Assuming that you want to plot a histogram and chosing the third option, a possible solution may look something like this (based on a histogram2d)

import matplotlib.pyplot as plt
import numpy as np

xedges = [0, 1, 1.5, 3, 5]
yedges = [0, 2, 3, 4, 6]

# produce histogram
x = np.random.normal(2.5, 1, 100)
y = np.random.normal(1.5, 1, 100)
H, xedges, yedges = np.histogram2d(y, x, bins=(xedges, yedges))

fig=plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Something')
X, Y = np.meshgrid(xedges, yedges)
im = ax.pcolormesh(X, Y, H)

# label the histogram bins
for i in range(len(yedges)-1):
    for j in range(len(xedges)-1):
        ax.text( (xedges[j+1]-xedges[j])/2.+xedges[j] , 
                 (yedges[i+1]-yedges[i])/2.+yedges[i] , 
                str(H[i, j]) , ha="center", va="center", color="w", fontweight="bold")
plt.colorbar(im)        

plt.show()

enter image description here

Upvotes: 1

Related Questions