简体   繁体   中英

how to display results as titles on multiple plots in one image output (python matplotlib)?

What i have done: I am plotting mean values of a distribution of 'v' values on an xy grid. I choose only those cells in the grid that have mean>2 and I plot them and make them appear as a single image on my console (jupyter notebook).

What I want to do: I want the mean value of each plot to appear as the title of that particular plot in image. Any ideas on how to do that? Thanks!

The full code is:

import matplotlib.pyplot as plt
import numpy as np

x=np.array([11,12,12,13,21,14])
y=np.array([28,5,15,16,12,4])
v=np.array([10,5,2,10,6,7])

x = x // 4 
y = y // 4 
k=10
cells = [[[] for y in range(k)] for x in range(k)] #creating cells or pixels on x-y plane

#letting v values to fall into the grid cells
for ycell in range(k):
    for xcell in range(k):
        cells[ycell][xcell] = v[(y  == ycell) & (x  == xcell)]
        
for ycell in range(k):
     for xcell in range(k):
        this = cells[ycell][xcell] 
        
#getting mean from velocity values in each cell
mean_v = [[[] for y in range(k)] for x in range(k)]
to_plot = []

for ycell in range(k):
    for xcell in range(k):
        cells[ycell][xcell] = v[(y== ycell) & (x== xcell)]
        mean_v[ycell][xcell] = np.mean(cells[ycell][xcell])
        #h3_pixel=h3[ycell][xcell]
        if mean_v[ycell][xcell]>2:
            to_plot.append(cells[ycell][xcell])
            
plt.rcParams["figure.figsize"] = (20, 10)

SIZE = 5   
f, ax = plt.subplots(SIZE,SIZE)

for idx, data in enumerate(to_plot):
    x = idx % SIZE
    y = idx // SIZE
    ax[y, x].hist(data)
plt.show()           

In your list to_plot , you can hold tuples of (cell, title) and then use set_title to set the title of each subplot.

for ycell in range(k):
    for xcell in range(k):
        cells[ycell][xcell] = v[(y== ycell) & (x== xcell)]
        mean_v[ycell][xcell] = np.mean(cells[ycell][xcell])
        if mean_v[ycell][xcell]>2:
            to_plot.append((cells[ycell][xcell], mean_v[ycell][xcell]))
            
plt.rcParams["figure.figsize"] = (20, 10)

SIZE = 5   
f, ax = plt.subplots(SIZE,SIZE)

for idx, data in enumerate(to_plot):
    x = idx % SIZE
    y = idx // SIZE
    ax[y, x].hist(data[0])
    ax[y, x].set_title(f'Mean = {data[1]}')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM