Skip to content

Visualization of Bin1 and Cell Bin Data

Guang-Wei Zhang edited this page Aug 22, 2023 · 2 revisions
import stereo as st
import warnings
warnings.filterwarnings('ignore')
file_list = [
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef']

data_path = file_list[8]
print(data_path)
data = st.io.read_gef(file_path=data_path, bin_type='cell_bins')
data.tl.cal_qc()
data.plt.spatial_scatter(show_ticks=True)   
]

Introduction:

The provided script focuses on visualizing data from stereo sequencing, specifically targeting Bin1 and Cell Bin data types. The main aim is to enhance comprehension and insights by rendering a spatial scatter plot of the data.

Steps:

1. Setup and Configuration:

  • Libraries: The script uses the stereo library, abbreviated as st, which contains methods and tools for processing and visualizing stereo sequencing data. Furthermore, the warnings library is utilized to suppress any unwanted warnings that might occur during the processing.
import stereo as st
import warnings
warnings.filterwarnings('ignore')

2. Input Data List:

  • The file_list contains paths to several .gef files, each named with a Chip_ID. These files contain the stereo sequencing data needed for visualization.
file_list = [
    'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef',
    # ... [other file paths]
    'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX.gef'
]

3. Data Selection and Processing:

  • The script, as written, specifically chooses the data at index 8 (i.e., the path ending in B01204C2.cellbin.gef) from the file_list for visualization.
data_path = file_list[8]
print(data_path)

4. Data Reading and Visualization:

  • The chosen .gef file is read using st.io.read_gef, indicating that the bin type is 'cell_bins'.

  • After loading the data, quality control metrics are calculated with the cal_qc method.

  • Finally, a spatial scatter plot is generated to visualize the Bin1 and Cell Bin data. The plot includes coordinate ticks for clarity.

data = st.io.read_gef(file_path=data_path, bin_type='cell_bins')
data.tl.cal_qc()
data.plt.spatial_scatter(show_ticks=True)

Concluding Remarks:

This script provides a streamlined way to visualize stereo sequencing data, especially focusing on Bin1 and Cell Bin data types. By leveraging the tools and methods in the stereo library, researchers and analysts can gain valuable insights into their data's spatial distribution.

Note: Users intending to visualize different .gef files should adjust the index of file_list accordingly.

Wiki: Visualization of Bin1 Data Using h5ad Files


Visulization of bin1 data (input is h5ad files)

import numpy as np
import scanpy as sc
from matplotlib.colors import Normalize
from matplotlib.cm import get_cmap
from PIL import Image
import os


def load_h5ad(filename):
    # Load the .h5ad file
    adata = sc.read(filename)
    return adata

def plot_raster(adata, filename):
    # Get the 'x', 'y' coordinates
    x_coords = adata.obs['x'].values
    y_coords = adata.obs['y'].values
 
    # Get the minimum x and y values
    min_x = int(x_coords.min())
    min_y = int(y_coords.min())

    # Translate the coordinates so they start from 0
    x_coords -= min_x
    y_coords -= min_y

    # Sum the expression values along the genes axis to get the total gene counts for each cell
    gene_counts = adata.X.sum(axis=1).A1

    # Determine the dimensions of the plot based on the translated coordinates
    x_max = int(x_coords.max())
    y_max = int(y_coords.max())

    # Create an empty image with a white background
    image = np.ones((y_max + 1, x_max + 1, 3), dtype=np.uint8) * 255

    # Normalize the gene counts to map them to a color
    norm = Normalize(vmin=gene_counts.min(), vmax=gene_counts.max())
    colormap = get_cmap('viridis')

    # Fill the image with colors based on the gene counts
    # Fill the image with colors based on the gene counts
    for x, y, count in zip(x_coords.astype(int), y_coords.astype(int), gene_counts):
        color = colormap(norm(count))[:3]  # Get RGB color without alpha
        color = (np.array(color) * 255).astype(np.uint8) # Convert to 8-bit integer
        image[y, x] = color


    # Create and save the image using PIL
    image_pil = Image.fromarray(image)
    image_pil.save(filename + '_bin1.png')





directory = r'/media/zhang/Elements1/spinalcord_gef_files/B01204C2'

# Iterate through all the files in the directory
for filename in os.listdir(directory):
    # Check if the file is an h5ad file
    if filename.endswith('.h5ad'):
        full_path = os.path.join(directory, filename)
        adata = load_h5ad(full_path)

        # Call the plot_raster function to plot the total gene counts
        plot_raster(adata, full_path)

Introduction:

This guide discusses a Python script aimed at visualizing Bin1 data extracted from .h5ad files, which are commonly used in single-cell analyses. The script generates raster plots that represent the spatial distribution of total gene counts for each cell, highlighting regions of high gene expression.

Steps:

1. Import Necessary Libraries:

  • Essential libraries, such as scanpy, numpy, and PIL, are imported to facilitate data handling, manipulation, and visualization.
import numpy as np
import scanpy as sc
from matplotlib.colors import Normalize
from matplotlib.cm import get_cmap
from PIL import Image
import os

2. Function Definitions:

  • load_h5ad(filename):

    • This function loads a given .h5ad file into an AnnData object for further processing.
    • Input: Path to .h5ad file.
    • Output: AnnData object.
  • plot_raster(adata, filename):

    • Visualizes and saves a raster plot from the provided AnnData object.
    • Input:
      1. AnnData object.
      2. Filename (to save the generated raster plot).
    • Output: A .png image showing the spatial distribution of total gene counts.

3. Directory Processing:

  • The script is set to operate on all .h5ad files located within a specified directory.
directory = r'/media/zhang/Elements1/spinalcord_gef_files/B01204C2'
  • For each .h5ad file found, the script:
    1. Loads the file into an AnnData object using load_h5ad.
    2. Processes and visualizes the data using plot_raster.
for filename in os.listdir(directory):
    if filename.endswith('.h5ad'):
        full_path = os.path.join(directory, filename)
        adata = load_h5ad(full_path)
        plot_raster(adata, full_path)

Key Points:

  • Raster Plot: This visualization method uses a grid of colored pixels (or squares) to represent data. For this script, the color intensity of each pixel corresponds to the total gene counts for each cell in that spatial region.

  • Normalization: The script uses the Normalize class from Matplotlib to adjust gene count values so that they can be mapped to colors using the viridis colormap.

  • Output: The generated plots are saved as .png images within the same directory as the input .h5ad files. Each output image is named after the original .h5ad file, with an _bin1.png suffix.


Conclusion:

By leveraging the efficiency of Python and the capabilities of scanpy, this script offers a straightforward method to visualize and interpret Bin1 data from .h5ad files. Through the generated raster plots, researchers can gain a clear picture of gene expression patterns in their datasets.