```r
---
title: "OrgHeatmap Tutorial"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{OrgHeatmap Tutorial}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
  %\VignetteDepends{OrgHeatmap} 
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  dev = "png",  
  dpi = 150
)
```

```{r setup}
library(OrgHeatmap)
```



## 1. Package Introduction

`OrgHeatmap` is an R package for visualizing numerical data (such as gene expression, protein abundance, or physiological indicators) on anatomical maps of human, mouse, and organelle structures. It provides flexible customization options for color schemes, organ system filtering, and quantitative comparisons.



## 2. Installation and Data Preparation

### 2.1 Package Installation
```r
# Install from local source
install.packages("OrgHeatmap_0.3.1.tar.gz", repos = NULL, type = "source")

# Or install from GitHub
# devtools::install_github("QiruiShen439/OrgHeatmap")

# Install dependencies if needed
install.packages(c("ggpolypath", "patchwork", "dplyr", "stringdist", "ggplot2", "sf", "viridis"))
```

### 2.2 Loading Example Data
The package includes comprehensive example datasets:
```r
# Load built-in example datasets
data_path <- system.file("extdata", "exampledata.Rdata", package = "OrgHeatmap")
load(data_path)

# Check available datasets
ls(pattern = "example_Data")
```

```{r data-preview, echo=FALSE}
# Preview example data structure
data_path <- system.file("extdata", "exampledata.Rdata", package = "OrgHeatmap")
load(data_path)
cat("Example Data 1 (Mouse):\n")
print(head(example_Data1))
cat("\nExample Data 3 (Human):\n")
print(head(example_Data3))
```



## 3. Basic Visualization

### 3.1 Simple Organ Visualization
```r
# Basic visualization with default parameters
result <- OrgHeatmap(data = example_Data3)
print(result$plot)
```

### 3.2 Understanding Output Structure
The function returns a comprehensive list with multiple components:
```r
# Explore returned results
names(result)
```

Key components:
- `plot`: Visualization object (ggplot2)
- `clean_data`: Processed data with standardized organ names
- `system_used`: Organ system used for filtering
- `mapped_organs`: Successfully mapped organ names
- `missing_organs`: Organs without coordinate data
- `total_value`: Sum of all values



## 4. Core Features

### 4.1 Multi-Species Support
```r
# Human visualization (default)
human_result <- OrgHeatmap(example_Data3, title = "Human Organ Visualization")

# Mouse visualization
mouse_result <- OrgHeatmap(
  data = example_Data1,
  species = "mouse",
  system = "digestive",
  title = "Mouse Digestive System"
)

# Organelle visualization
organelle_data <- data.frame(
  organ = c("mitochondrion", "nucleus", "endoplasmic_reticulum"),
  value = c(15.2, 8.7, 6.3)
)
organelle_result <- OrgHeatmap(
  data = organelle_data,
  species = "organelle",
  title = "Organelle Expression"
)
```

### 4.2 Organ System Filtering
```r
# Filter by specific organ system
circulatory_plot <- OrgHeatmap(
  data = example_Data3,
  system = "circulatory",
  title = "Circulatory System Data"
)

# View available systems for human
unique(human_organ_systems$system)
```

### 4.3 Advanced Color Configuration

#### Using RColorBrewer Palettes
```r
# Unified color scheme with palette
palette_plot <- OrgHeatmap(
  data = example_Data3,
  palette = "PuBuGn",
  reverse_palette = TRUE,
  title = "PuBuGn Palette (Reversed)"
)
```

#### Custom Color Gradients
```r
# Custom 2-color gradient
custom_2color <- OrgHeatmap(
  data = example_Data3,
  color_low = "#FFE4E1",
  color_high = "#DC143C",
  title = "Custom 2-Color Gradient"
)

# Custom 3-color gradient
custom_3color <- OrgHeatmap(
  data = example_Data3,
  color_low = "#FF0000",
  color_mid = "#FFFF00", 
  color_high = "#0000FF",
  title = "Custom 3-Color Gradient"
)
```

#### Separate Bar Chart Colors
```r
# Different colors for heatmap and bar chart
separate_colors <- OrgHeatmap(
  data = example_Data3,
  color_low = "#F7FBFF",
  color_high = "#08306B",
  organbar_low = "#FFF7BC",
  organbar_high = "#D95F0E",
  organbar = TRUE,
  title = "Separate Heatmap/Bar Colors"
)
```

### 4.4 Bar Chart Configuration
```r
# Enable bar chart with customization
bar_chart_plot <- OrgHeatmap(
  data = example_Data3,
  organbar = TRUE,
  organbar_title = "Expression Level",
  organbar_digit = 2,
  organbar_color = "skyblue",  # Solid color for bars
  title = "Custom Bar Chart"
)
```

### 4.5 Organ Name Mapping and Standardization
```r
# Handle non-standard organ names
custom_mapping <- c(
  "adrenal" = "adrenal_gland",
  "lymph node" = "lymph_node", 
  "soft tissue" = "muscle"
)

mapped_result <- OrgHeatmap(
  data = example_Data3,
  organ_name_mapping = custom_mapping,
  title = "Custom Organ Name Mapping"
)
```

### 4.6 Data Aggregation Methods
```r
# Example data with duplicate organs
dup_data <- data.frame(
  organ = c("heart", "heart", "liver", "brain", "brain", "brain"),
  value = c(10, 20, 15, 5, 10, 15)
)

# Mean aggregation
mean_result <- OrgHeatmap(
  data = dup_data,
  aggregate_method = "mean",
  title = "Mean Aggregation"
)

# Sum aggregation  
sum_result <- OrgHeatmap(
  data = dup_data,
  aggregate_method = "sum",
  title = "Sum Aggregation"
)
```

### 4.7 Display Options
```r
# Show all organ outlines for anatomical context
showall_plot <- OrgHeatmap(
  data = example_Data3,
  showall = TRUE,
  fillcolor_other = "#D3D3D3",
  title = "All Organ Outlines Displayed"
)

# Hide body outline
no_outline <- OrgHeatmap(
  data = example_Data3,
  outline = FALSE,
  title = "Without Body Outline"
)
```



## 5. Advanced Usage

### 5.1 Custom Organ System Mapping
```r
# Extend default organ system mapping
custom_system_map <- rbind(
  human_organ_systems,
  data.frame(
    organ = c("prostate", "custom_organ"),
    system = c("reproductive", "custom_system"),
    stringsAsFactors = FALSE
  )
)

custom_system_result <- OrgHeatmap(
  data = example_Data3,
  organ_system_map = custom_system_map,
  system = "custom_system",
  title = "Custom Organ System"
)
```

### 5.2 Column Name Customization
```r
# Data with custom column names
custom_data <- data.frame(
  organ_name = c("heart", "liver", "brain"),
  expression_level = c(15, 25, 20)
)

custom_col_result <- OrgHeatmap(
  data = custom_data,
  organ_col = "organ_name",
  value_col = "expression_level",
  title = "Custom Column Names"
)
```

### 5.3 Saving Results
```r
# Save plot and cleaned data
save_result <- OrgHeatmap(
  data = example_Data3,
  save_plot = TRUE,
  plot_path = file.path(tempdir(), "my_visualization.png"),
  plot_width = 12,
  plot_height = 10,
  plot_dpi = 300,
  save_clean_data = TRUE,
  clean_data_path = file.path(tempdir(), "cleaned_data.rds"), 
  title = "Saved Visualization"
)

# Access saved files
list.files(path = tempdir(),pattern = "my_visualization|cleaned_data")
```



## 6. Color System Priority

The package uses a unified color system with clear priority levels:

### Priority Order:
1. **Highest**: `organbar_low`/`organbar_high` (bar chart colors)
2. **Medium**: `color_low`/`color_high`/`color_mid` (heatmap colors)  
3. **Lowest**: `palette` with optional `reverse_palette`

### Example demonstrating priority:
```r
# organbar colors take precedence
priority_example <- OrgHeatmap(
  data = example_Data3,
  organbar_low = "blue",      # Highest priority
  color_low = "red",          # Overridden by organbar_low
  palette = "YlOrRd",         # Lowest priority
  organbar = TRUE,
  title = "Color Priority Example"
)
```



## 7. Troubleshooting Common Issues

### 7.1 Missing Organ Coordinates
```r
# Check available organs for each species
cat("Human organs:", names(human_organ_coord), "\n")
cat("Mouse organs:", names(mouse_organ_coord), "\n") 
cat("Organelle organelles:", names(organelle_organ_coord), "\n")

# Filter valid organs only
valid_result <- OrgHeatmap(
  data = example_Data3,
  valid_organs = c("heart", "liver", "brain", "kidney")
)
```

### 7.2 Invalid Color Specifications
```r
# Validate RColorBrewer palettes
RColorBrewer::brewer.pal.info

# Valid viridis options
c("viridis", "plasma", "magma", "inferno", "cividis")
```

### 7.3 Installation Issues
```r
# Install all dependencies
install.packages(c("sf", "ggpolypath", "patchwork", "stringdist", "viridis"))

# Check package loading
library(OrgHeatmap)
packageVersion("OrgHeatmap")
```



## 8. Performance Tips

### 8.1 For Large Datasets
```r
# Use system filtering to reduce rendering time
filtered_plot <- OrgHeatmap(
  data = large_dataset,
  system = "specific_system",
  showall = FALSE
)
```

### 8.2 High-Resolution Output
```r
# For publication-quality figures
publication_plot <- OrgHeatmap(
  data = example_Data3,
  save_plot = TRUE,
  plot_path = file.path(tempdir(), "publication_figure.tiff"), 
  plot_width = 8,
  plot_height = 6,
  plot_dpi = 600,
  plot_device = "tiff"
)
```



## 9. Summary

`OrgHeatmap` provides comprehensive tools for biological data visualization with the following key features:

| Feature | Key Parameters |
|---------|----------------|
| Multi-species | `species = "human"/"mouse"/"organelle"` |
| System filtering | `system`, `organ_system_map` |
| Color configuration | `palette`, `color_low/color_high`, `organbar_low/organbar_high` |
| Bar charts | `organbar`, `organbar_title`, `organbar_color` |
| Name standardization | `organ_name_mapping` |
| Data aggregation | `aggregate_method = "mean"/"sum"/"count"` |
| Output control | `save_plot`, `save_clean_data` |

For complete parameter documentation: `?OrgHeatmap`


The package is designed to handle real-world biological data challenges including non-standard organ names, duplicate entries, and flexible visualization requirements across multiple species and subcellular structures.

