[
  {
    "path": ".Rbuildignore",
    "content": "^.*\\.Rproj$\n^\\.Rproj\\.user$\nMakefile\n^CONDUCT\\.md$\nREADME.Rmd\nREADME.md\nTODO.md\nRplots.pdf\n^\\.dev$\n"
  },
  {
    "path": ".dev/cnetplot_comparecluster_design.md",
    "content": "# compareCluster cnetplot Design Draft\n\n## Goal\nUpdate `enrichplot::cnetplot.compareClusterResult()` so that `compareCluster` pies behave consistently with the newer `ggtangle::cnetplot()` sizing model, while keeping the current visual style and minimizing API breakage.\n\nThe immediate goals are:\n- Make `categorySizeBy` actually affect category pie size for `compareClusterResult`.\n- Clarify how pie colors should be customized.\n- Align `enrichplot` documentation with the current `ggtangle` semantics.\n\n## Current State\n\n### Data Flow\n- `cnetplot.enrichResult()` and `cnetplot.gseaResult()` convert the enrichment object to gene sets, attach numeric term-level columns as attributes, and pass `categorySizeBy` through to `ggtangle::cnetplot()`.\n- `cnetplot.compareClusterResult()` takes a different route:\n  - `tidy_compareCluster()` produces a long data frame.\n  - Gene sets are reconstructed from `Description`.\n  - `ggtangle::cnetplot()` is called with `size_category = 0`, `size_item = 0`, and `node_label = \"none\"` to generate only the network layout.\n  - `add_node_pie()` overlays category and gene nodes with `scatterpie::geom_scatterpie()`.\n\n### Consequences\n- The visible category nodes in `compareClusterResult` are not the base `ggtangle` points. They are pies added later in `add_node_pie()`.\n- `categorySizeBy` is currently declared in the `compareClusterResult` method signature, but it is not passed to `ggtangle::cnetplot()` and it is not used inside `add_node_pie()`.\n- Category pie radius is currently derived from summed `Count` values per term, scaled by `size_category`.\n- Pie fill colors are currently determined by the `Cluster` columns passed to `scatterpie`, not by `color_category`.\n\n## Problem Statement\nThe current implementation has three mismatches.\n\n### 1. API Mismatch\n`categorySizeBy` is exposed for `compareClusterResult`, but the argument has no effect on the category pie radius.\n\n### 2. Semantic Mismatch\n`ggtangle::cnetplot()` now supports expression/formula-based category sizing such as `~itemNum` and `~ -log10(p.adjust)`, but the `compareClusterResult` path still uses a hard-coded size computation based on total `Count`.\n\n### 3. Documentation Mismatch\nThe `enrichplot` docs still describe `categorySizeBy` using the older wording (\"itemNum\", \"pvalue\", \"p.adjust\", \"qvalue\" or numeric vector), which no longer reflects the current `ggtangle` interface.\n\n## Design Principles\n- Preserve the current `compareCluster` visual style based on pies.\n- Keep the change local to `enrichplot`; do not require new behavior from `ggtangle`.\n- Reuse `ggtangle` sizing semantics as much as practical.\n- Prefer minimal API expansion.\n- Avoid silently changing gene-node pie behavior unless explicitly intended.\n\n## Proposed Changes\n\n### 1. Separate Layout Generation from Pie Radius Computation\nKeep the current two-step approach:\n- Step 1: use `ggtangle::cnetplot()` only to compute layout and edges.\n- Step 2: use `add_node_pie()` to draw visible nodes.\n\nNo change is needed to the basic rendering architecture.\n\n### 2. Introduce a Term-Level Size Evaluation Step\nAdd an internal helper that computes one numeric size value per category term before pies are drawn.\n\nSuggested helper:\n- `compute_comparecluster_category_size(d, categorySizeBy)`\n\nResponsibilities:\n- Start from the `tidy_compareCluster()` output.\n- Build one row per `Description`.\n- Preserve numeric term-level columns needed for evaluation, such as:\n  - `Count` summary\n  - `pvalue`\n  - `p.adjust`\n  - `qvalue`\n  - any other numeric columns that are constant within a term\n- Add an explicit `itemNum` column representing the number of unique genes in each term.\n- Evaluate `categorySizeBy` against this term-level data.\n\n### 3. Adopt Formula/Expression Semantics for `compareClusterResult`\nNormalize `categorySizeBy` in `cnetplot.compareClusterResult()` to match `ggtangle::cnetplot.list()` behavior:\n- Default to `~itemNum`.\n- Accept bare expressions such as `p.adjust`.\n- Accept formulas such as `~ -log10(p.adjust)`.\n- Accept scalar numeric values, which should recycle to all categories.\n\nThis avoids having `compareClusterResult` behave differently from `enrichResult`.\n\n### 4. Use Evaluated Size Values as Pie Radius Inputs\nModify `add_node_pie()` to accept precomputed category size values.\n\nSuggested signature:\n- `add_node_pie(p, d, pie = \"equal\", category_scale = 1, item_scale = 1, category_size = NULL)`\n\nBehavior:\n- If `category_size` is `NULL`, preserve existing `Count`-based behavior for backward compatibility.\n- If `category_size` is provided, map it to category `Description` and use it as the base value for pie radius.\n\nImportant detail:\n- The current code multiplies by `category_scale` twice: once when computing `dd$pathway_size`, and once again in `aes(r = pathway_size * category_scale)`.\n- The redesign should make scaling single-source and explicit.\n\nRecommended rule:\n- Compute a normalized base radius from `category_size`.\n- Apply `category_scale` exactly once when converting the normalized value to plotted radius.\n\n### 5. Keep Gene Pie Size Behavior Unchanged\nFor this change, keep gene-node pie size fixed as it is today.\n\nReason:\n- The issue is specifically about category node sizing.\n- Changing item-node sizing in the same patch would expand scope and complicate validation.\n\n### 6. Clarify Color Customization Strategy\nDo not overload `color_category` to mean pie slice fill colors.\n\nRecommended behavior:\n- Keep `color_category` semantics unchanged for non-pie category nodes.\n- Document that `compareCluster` pie slice colors are controlled by the fill scale.\n- In examples and docs, show customization via `scale_fill_manual()`.\n\nOptional future enhancement:\n- Add a new parameter such as `pie_colors = NULL` to apply a manual fill scale internally.\n\nThis should not be part of the minimal fix unless a stronger convenience API is desired.\n\n## Implementation Sketch\n\n### `cnetplot.compareClusterResult()`\n- Change default `categorySizeBy` from `NULL` to `~itemNum`.\n- Compute `category_size <- compute_comparecluster_category_size(d, categorySizeBy)`.\n- Keep the existing `ggtangle::cnetplot()` call for layout generation.\n- Pass `category_size` into `add_node_pie()`.\n\n### `compute_comparecluster_category_size()`\n- Build a term-level summary table keyed by `Description`.\n- Add `itemNum` as unique gene count per term.\n- Summarize `Count` as total term count across clusters.\n- For columns like `p.adjust`, `pvalue`, `qvalue`, use one representative value per term if they are invariant within term.\n- If a requested variable is not available, raise a clear error that names the missing field.\n- Validate that the evaluated result is numeric, length 1 or `n_terms`, and contains no `NA`.\n\n### `add_node_pie()`\n- Use `category_size` instead of hard-coded `pathway_size` when supplied.\n- Normalize category radii in a stable way so legends remain interpretable.\n- Update the legend labeller accordingly.\n\n## Open Design Choice\n\n### How should pie legend labels behave when `categorySizeBy` is not `Count`?\nThere are two reasonable options.\n\nOption A: keep a numeric radius legend only\n- The legend shows the numeric values produced by `categorySizeBy`.\n- Best for expressions like `-log10(p.adjust)`.\n- Most faithful to the actual radius mapping.\n\nOption B: keep the current gene-count-style legend when possible\n- Use count labels only when the size source is effectively count-based.\n- Switch to numeric-value labels for all other cases.\n\nRecommendation:\n- Use Option A as the general rule.\n- If `categorySizeBy` is exactly `~itemNum` or equivalent count-based behavior, labels can remain count-like.\n\n## Backward Compatibility\n- Existing plots without `categorySizeBy` should continue to work.\n- Existing visual style should remain close to current behavior when using the default.\n- Existing code that adds `scale_fill_manual()` after `cnetplot(compareClusterResult)` should continue to work.\n\nPotential visible changes:\n- Default pie radii may shift slightly if the new default is implemented through normalized `itemNum` rather than the current summed `Count` rule.\n- Pie legend labels may change if they are tied to the new size source.\n\n## Documentation Changes\n\n### `R/cnetplot.R` roxygen\n- Update the `categorySizeBy` description for all relevant methods to match current expression/formula semantics.\n- For `compareClusterResult`, explicitly state that the argument controls category pie size.\n- Add examples using:\n  - `categorySizeBy = ~itemNum`\n  - `categorySizeBy = ~ -log10(p.adjust)`\n  - `scale_fill_manual()` for cluster pie colors\n\n### `man/cnetplot.Rd`\n- Regenerate documentation after roxygen updates.\n\n### NEWS\n- Add an entry describing:\n  - `categorySizeBy` now works for `compareClusterResult` category pies\n  - pie color customization should use fill scales\n  - improved consistency with `ggtangle::cnetplot()`\n\n## Verification Plan\n\n### Manual Verification\nCreate a script under `.dev`, for example:\n- `.dev/test_cnetplot_comparecluster_size.R`\n\nCheck at least the following cases:\n1. Default `compareCluster` plot with no explicit `categorySizeBy`\n2. `categorySizeBy = ~itemNum`\n3. `categorySizeBy = ~ -log10(p.adjust)`\n4. `categorySizeBy = 2`\n5. `scale_fill_manual()` on cluster pies\n6. GSEA-style `compareCluster` result if available through `core_enrichment`\n\n### Behavior Checks\n- Category pie radii change when `categorySizeBy` changes.\n- Gene pie radii remain unchanged.\n- Edge layout is unaffected.\n- Labels still align with category nodes.\n- The pie legend remains readable and correctly reflects the size source.\n\n### Error Handling Checks\n- Unknown variable in `categorySizeBy` gives a clear error.\n- Non-numeric evaluation gives a clear error.\n- `NA` output from the size expression gives a clear error.\n\n## Non-Goals\n- Redesigning the overall `compareCluster` cnetplot appearance.\n- Changing gene pie size semantics.\n- Adding a new high-level palette API unless needed after the minimal fix.\n- Refactoring `enrichResult` and `gseaResult` methods beyond documentation alignment.\n\n## Recommended Implementation Order\n1. Add the internal term-level size computation helper.\n2. Thread computed `category_size` into `add_node_pie()`.\n3. Fix radius scaling so `category_scale` is applied exactly once.\n4. Update roxygen and examples.\n5. Add a small manual test script under `.dev`.\n"
  },
  {
    "path": ".dev/manhattan_plot_plan.md",
    "content": "# Manhattan Plot Implementation Plan\n\n## Goal\nImplement a `manhattanplot()` function in the `enrichplot` package to visualize enrichment results as a Manhattan plot, drawing conceptual inspiration from `gprofiler2::gostplot` (Figure 1 of f1000research paper 9-709). The plot will display enriched terms across the X-axis and their significance (-log10 P-value) on the Y-axis.\n\n## Proposed Changes\n\n### R/AllGenerics.R\n- **[MODIFY] R/AllGenerics.R**\n  Add the generic function `manhattanplot` to support S4 method dispatch.\n  ```R\n  #' Manhattan plot for enrichment result\n  #'\n  #' @title manhattanplot\n  #' @rdname manhattanplot\n  #' @param x enrichment result.\n  #' @param ... additional parameters.\n  #' @return ggplot object\n  #' @export\n  setGeneric(\"manhattanplot\", function(x, ...) {\n      standardGeneric(\"manhattanplot\")\n  })\n  ```\n\n### R/manhattanplot.R\n- **[NEW] R/manhattanplot.R**\n  Create a new S4 method implementation file to house `manhattanplot`.\n  - Define methods for `enrichResult`, `gseaResult`, `compareClusterResult`, `enrichResultList`, and `gseaResultList` (similar to `dotplot.R`).\n  - **Visualization Logic**: \n    - Use `fortify()` to convert the `x` enrichment object into a `df` data frame.\n    - **X-axis**: Enriched terms (`Description`), ordered or grouped by category (e.g. `ONTOLOGY`, `Cluster`, or semantic similarity if `pairwise_termsim` was used). By default, they will follow the base `fortify()` order or `orderBy` parameter. Note: standard Manhattan plots space the points evenly or group by semantic similarities.\n    - **Y-axis**: Computed significance, representing `-log10(p.adjust)` (or `-log10(pvalue)` if specified).\n    - **Size**: Point size maps to the gene `Count`.\n    - **Color**: Point color maps to the grouping variable (e.g., `ONTOLOGY`, dataset `Cluster`, or default to `p.adjust` gradient if un-grouped).\n    - **Styling**: Integrate standard `enrichplot` configurations, including `theme_dose(font.size)` and `enrichplot_point_shape`. Incorporate an optional horizontal dashed line referencing significant thresholds (e.g. `yintercept = -log10(0.05)`).\n    - Return the resulting `ggplot` object.\n\n## Verification Plan\n\n### Manual Verification\nVerification will be performed via manual inspection with standard DOSE/clusterProfiler data.\n\nA script (`.dev/test_manhattan.R`) will be composed to iteratively test:\n1. **Single Enrichment**: `DOSE::enrichDO()` to ensure un-grouped Manhattan plotting handles axes and coloring correctly.\n2. **Compared Clusters**: `clusterProfiler::compareCluster()` to verify grouped coloring, facet behaviors (if implemented), and spacing.\n3. Check visual properties:\n   - Make sure X-axis labels are readable or omitted effectively (Manhattan plots often omit strict x-axis text in favor of broad grouping or interactive labels).\n   - Confirm Y-axis correctly shows the log scale of significance.\n   - Point sizes scale predictably by `Count`.\n"
  },
  {
    "path": ".gitignore",
    "content": ".Rproj.user\n.Rhistory\n.RData\n*.DS_Store\n*html\n\n.vscode/\nRplots*\n*.log\nRplots.pdf\n"
  },
  {
    "path": "CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, we pledge to respect all people who \ncontribute through reporting issues, posting feature requests, updating documentation,\nsubmitting pull requests or patches, and other activities.\n\nWe are committed to making participation in this project a harassment-free experience for\neveryone, regardless of level of experience, gender, gender identity and expression,\nsexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.\n\nExamples of unacceptable behavior by participants include the use of sexual language or\nimagery, derogatory comments or personal attacks, trolling, public or private harassment,\ninsults, or other unprofessional conduct.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments,\ncommits, code, wiki edits, issues, and other contributions that are not aligned to this \nCode of Conduct. Project maintainers who do not follow the Code of Conduct may be removed \nfrom the project team.\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by \nopening an issue or contacting one or more of the project maintainers.\n\nThis Code of Conduct is adapted from the Contributor Covenant \n(http:contributor-covenant.org), version 1.0.0, available at \nhttp://contributor-covenant.org/version/1/0/0/\n"
  },
  {
    "path": "DESCRIPTION",
    "content": "Package: enrichplot\nTitle: Visualization of Functional Enrichment Result\nVersion: 1.33.0\nAuthors@R: c(\n    person(given = \"Guangchuang\", family = \"Yu\", email = \"guangchuangyu@gmail.com\",   role  = c(\"aut\", \"cre\"), comment = c(ORCID = \"0000-0002-6485-8781\")),\n    person(given = \"Chun-Hui\", family = \"Gao\", email = \"gaospecial@gmail.com\", role = \"ctb\", comment = c(ORCID = \"0000-0002-1445-7939\")))\nDescription: The 'enrichplot' package provides visualization methods for interpreting functional enrichment results from ORA or GSEA analyses. \n    It is designed to work with the 'clusterProfiler' ecosystem and builds on 'ggplot2' for flexible and extensible graphics.\nDepends: R (>= 4.2.0)\nImports:\n    aplot (>= 0.2.1),\n    DOSE,\n    dplyr,\n    enrichit,\n    ggfun (>= 0.1.7),\n    ggnewscale,\n    ggplot2 (>= 3.5.0),\n    ggrepel (>= 0.9.0),\n    ggtangle (>= 0.0.9),\n    ggtree,\n    GOSemSim (>= 2.37.2),\n    graphics,\n    grid,\n    igraph,\n    methods,\n    purrr,\n    RColorBrewer,\n    reshape2,\n    rlang,\n    scatterpie,\n    stats,\n    tidydr,\n    utils,\n    yulab.utils (>= 0.2.2)\nSuggests:\n    AnnotationDbi,\n    clusterProfiler,\n    europepmc,\n    ggarchery,\n    ggforce,\n    ggHoriPlot,\n    ggplotify,\n    ggridges,\n    ggstar,\n    ggtreeExtra,\n    ggupset,\n    glue,\n    grDevices,\n    gridExtra,\n    gson,\n    org.Hs.eg.db,\n    quarto,\n    scales,\n    tibble,\n    tidyr\nVignetteBuilder: quarto\nLicense: Artistic-2.0\nURL: https://yulab-smu.top/contribution-knowledge-mining/\nBugReports: https://github.com/GuangchuangYu/enrichplot/issues\nbiocViews: Annotation, GeneSetEnrichment, GO, KEGG,\n    Pathways, Software, Visualization\nEncoding: UTF-8\nRoxygenNote: 7.3.3\nRoxygen: list(markdown = TRUE)\n"
  },
  {
    "path": "Makefile",
    "content": "PKGNAME := $(shell sed -n \"s/Package: *\\([^ ]*\\)/\\1/p\" DESCRIPTION)\nPKGVERS := $(shell sed -n \"s/Version: *\\([^ ]*\\)/\\1/p\" DESCRIPTION)\nPKGSRC  := $(shell basename `pwd`)\nBIOCVER := RELEASE_3_23\n\n\nall: rd check clean\n\nfor-release: rd check-dontrun clean readme\n\nalldocs: rd\n\nrd:\n\tRscript -e 'roxygen2::roxygenise(\".\")'\n\nreadme:\n\tRscript -e 'rmarkdown::render(\"README.Rmd\")'\n\nbuild:\n\t# cd ..;\\\n\t# R CMD build $(PKGSRC)\n\tRscript -e 'devtools::build()'\n\nbuild2:\n\tcd ..;\\\n\tR CMD build --no-build-vignettes $(PKGSRC)\n\ninstall:\n\tcd ..;\\\n\tR CMD INSTALL $(PKGNAME)_$(PKGVERS).tar.gz\n\ncheck: \n\t# cd ..;\\\n\t# Rscript -e 'rcmdcheck::rcmdcheck(\"$(PKGNAME)_$(PKGVERS).tar.gz\")'\n\tRscript -e 'devtools::check()'\n\ncheck-dontrun: build\n\tcd ..;\\\n\tRscript -e 'rcmdcheck::rcmdcheck(\"$(PKGNAME)_$(PKGVERS).tar.gz\", args=c(\"--run-dontrun\"))'\n\n\ncheck2: build\n\tcd ..;\\\n\tR CMD check $(PKGNAME)_$(PKGVERS).tar.gz\n\nbioccheck:\n\tcd ..;\\\n\tRscript -e 'BiocCheck::BiocCheck(\"$(PKGNAME)_$(PKGVERS).tar.gz\")'\n\n\nclean:\n\tcd ..;\\\n\t$(RM) -r $(PKGNAME).Rcheck/\n\nrmrelease:\n\tgit branch -D $(BIOCVER)\n\nrelease:\n\tgit checkout $(BIOCVER);\\\n\tgit fetch --all\n\nupdate:\n\tgit fetch --all;\\\n\tgit checkout devel;\\\n\tgit merge upstream/devel;\\\n\tgit merge origin/devel\n\npush:\n\tgit push upstream devel;\\\n\tgit push origin devel\n\nbiocinit:\n\tgit remote add upstream git@git.bioconductor.org:packages/$(PKGNAME).git;\\\n\tgit fetch --all\n"
  },
  {
    "path": "NAMESPACE",
    "content": "# Generated by roxygen2: do not edit by hand\n\nS3method(as.data.frame,compareClusterResult)\nS3method(barplot,compareClusterResult)\nS3method(barplot,enrichResult)\nS3method(cnetplot,compareClusterResult)\nS3method(cnetplot,enrichResult)\nS3method(cnetplot,gseaResult)\nS3method(fortify,compareClusterResult)\nS3method(fortify,enrichResult)\nS3method(fortify,gseaResult)\nS3method(ggplot_add,autofacet)\nS3method(print,enrichplotDot)\nexport(autofacet)\nexport(cnetplot)\nexport(color_palette)\nexport(dotplot)\nexport(dotplot2)\nexport(emapplot)\nexport(facet_grid)\nexport(geneID)\nexport(geneInCategory)\nexport(geom_cnet_label)\nexport(geom_gsea_gene)\nexport(get_enrichplot_color)\nexport(ggtable)\nexport(ggtitle)\nexport(goplot)\nexport(gseaScores)\nexport(gseadist)\nexport(gseaplot)\nexport(gseaplot2)\nexport(gsearank)\nexport(heatplot)\nexport(hplot)\nexport(manhattanplot)\nexport(plot_list)\nexport(pmcplot)\nexport(ridgeplot)\nexport(set_enrichplot_color)\nexport(ssplot)\nexport(theme_dose)\nexport(treeplot)\nexport(upsetplot)\nexport(volplot)\nexportMethods(dotplot)\nexportMethods(emapplot)\nexportMethods(goplot)\nexportMethods(gseaplot)\nexportMethods(heatplot)\nexportMethods(manhattanplot)\nexportMethods(pairwise_termsim)\nexportMethods(ridgeplot)\nexportMethods(ssplot)\nexportMethods(treeplot)\nexportMethods(upsetplot)\nexportMethods(volplot)\nimport(GOSemSim)\nimportClassesFrom(enrichit,compareClusterResult)\nimportFrom(DOSE,theme_dose)\nimportFrom(RColorBrewer,brewer.pal)\nimportFrom(aplot,plot_list)\nimportFrom(dplyr,\"%>%\")\nimportFrom(dplyr,arrange)\nimportFrom(dplyr,bind_rows)\nimportFrom(dplyr,desc)\nimportFrom(dplyr,group_by)\nimportFrom(dplyr,mutate)\nimportFrom(dplyr,slice_head)\nimportFrom(dplyr,ungroup)\nimportFrom(enrichit,geneID)\nimportFrom(enrichit,geneInCategory)\nimportFrom(enrichit,gseaScores)\nimportFrom(ggfun,\"%<+%\")\nimportFrom(ggnewscale,new_scale_colour)\nimportFrom(ggnewscale,new_scale_fill)\nimportFrom(ggplot2,\"%+%\")\nimportFrom(ggplot2,aes)\nimportFrom(ggplot2,annotation_custom)\nimportFrom(ggplot2,coord_equal)\nimportFrom(ggplot2,coord_fixed)\nimportFrom(ggplot2,coord_flip)\nimportFrom(ggplot2,element_blank)\nimportFrom(ggplot2,element_line)\nimportFrom(ggplot2,element_rect)\nimportFrom(ggplot2,element_text)\nimportFrom(ggplot2,facet_grid)\nimportFrom(ggplot2,fortify)\nimportFrom(ggplot2,geom_bar)\nimportFrom(ggplot2,geom_blank)\nimportFrom(ggplot2,geom_boxplot)\nimportFrom(ggplot2,geom_col)\nimportFrom(ggplot2,geom_density)\nimportFrom(ggplot2,geom_hline)\nimportFrom(ggplot2,geom_jitter)\nimportFrom(ggplot2,geom_line)\nimportFrom(ggplot2,geom_linerange)\nimportFrom(ggplot2,geom_point)\nimportFrom(ggplot2,geom_rect)\nimportFrom(ggplot2,geom_segment)\nimportFrom(ggplot2,geom_text)\nimportFrom(ggplot2,geom_tile)\nimportFrom(ggplot2,geom_violin)\nimportFrom(ggplot2,geom_vline)\nimportFrom(ggplot2,ggplot)\nimportFrom(ggplot2,ggplotGrob)\nimportFrom(ggplot2,ggplot_add)\nimportFrom(ggplot2,ggplot_build)\nimportFrom(ggplot2,ggplot_gtable)\nimportFrom(ggplot2,ggtitle)\nimportFrom(ggplot2,guide_colorbar)\nimportFrom(ggplot2,guide_legend)\nimportFrom(ggplot2,guides)\nimportFrom(ggplot2,labs)\nimportFrom(ggplot2,margin)\nimportFrom(ggplot2,rel)\nimportFrom(ggplot2,scale_color_continuous)\nimportFrom(ggplot2,scale_color_gradient)\nimportFrom(ggplot2,scale_color_gradientn)\nimportFrom(ggplot2,scale_color_manual)\nimportFrom(ggplot2,scale_fill_continuous)\nimportFrom(ggplot2,scale_fill_discrete)\nimportFrom(ggplot2,scale_fill_gradient2)\nimportFrom(ggplot2,scale_fill_gradientn)\nimportFrom(ggplot2,scale_fill_manual)\nimportFrom(ggplot2,scale_size)\nimportFrom(ggplot2,scale_size_continuous)\nimportFrom(ggplot2,scale_x_continuous)\nimportFrom(ggplot2,scale_x_reverse)\nimportFrom(ggplot2,scale_y_continuous)\nimportFrom(ggplot2,scale_y_discrete)\nimportFrom(ggplot2,theme)\nimportFrom(ggplot2,theme_bw)\nimportFrom(ggplot2,theme_classic)\nimportFrom(ggplot2,theme_minimal)\nimportFrom(ggplot2,theme_void)\nimportFrom(ggplot2,xlab)\nimportFrom(ggplot2,xlim)\nimportFrom(ggplot2,ylab)\nimportFrom(ggrepel,geom_label_repel)\nimportFrom(ggrepel,geom_text_repel)\nimportFrom(ggtangle,cnetplot)\nimportFrom(ggtangle,geom_cnet_label)\nimportFrom(ggtangle,geom_edge)\nimportFrom(ggtree,geom_cladelab)\nimportFrom(ggtree,geom_hilight)\nimportFrom(ggtree,geom_tiplab)\nimportFrom(ggtree,geom_tippoint)\nimportFrom(ggtree,ggtree)\nimportFrom(ggtree,gheatmap)\nimportFrom(ggtree,groupClade)\nimportFrom(graphics,barplot)\nimportFrom(grid,arrow)\nimportFrom(grid,gpar)\nimportFrom(grid,unit)\nimportFrom(igraph,'E<-')\nimportFrom(igraph,'V<-')\nimportFrom(igraph,E)\nimportFrom(igraph,V)\nimportFrom(igraph,add_vertices)\nimportFrom(igraph,delete.edges)\nimportFrom(igraph,graph.empty)\nimportFrom(igraph,graph_from_data_frame)\nimportFrom(methods,is)\nimportFrom(methods,setGeneric)\nimportFrom(methods,setOldClass)\nimportFrom(purrr,map_df)\nimportFrom(rlang,.data)\nimportFrom(rlang,check_installed)\nimportFrom(rlang,sym)\nimportFrom(scatterpie,geom_scatterpie)\nimportFrom(scatterpie,geom_scatterpie_legend)\nimportFrom(stats,as.dist)\nimportFrom(stats,cutree)\nimportFrom(stats,hclust)\nimportFrom(stats,quantile)\nimportFrom(stats,setNames)\nimportFrom(tidydr,theme_dr)\nimportFrom(utils,data)\nimportFrom(utils,getFromNamespace)\nimportFrom(utils,head)\nimportFrom(utils,modifyList)\nimportFrom(yulab.utils,check_input)\nimportFrom(yulab.utils,get_cache_item)\nimportFrom(yulab.utils,str_wrap)\nimportFrom(yulab.utils,yulab_abort)\nimportFrom(yulab.utils,yulab_msg)\nimportFrom(yulab.utils,yulab_warn)\n"
  },
  {
    "path": "NEWS.md",
    "content": "# enrichplot 1.32.0\n\n+ Bioconductor RELEASE_3_23 (2026-04-29, Wed)\n\n# enrichplot 1.31.5\n\n+ `cnetplot.compareClusterResult()` now supports `categorySizeBy` for category pie sizing and aligns docs with `ggtangle::cnetplot()` semantics (2026-04-22, Wed)\n+ `ridgeplot` now supports `stat` parameter (default is 'density_ridges' and can be changed to 'binline') (2026-04-01, Wed, #343)\n+ manhattan plot for enriched result (2026-03-26, Thu)\n+ update roxygen document to use markdown syntax (2026-03-02, Mon)\n+ bug fixed in xy-lab format in `ssplot()` (2026-03-02, Mon)\n+ bug fixed in formula supports in `dotplot()` (2026-02-26, Thu)\n\n# enrichplot 1.31.4\n\n+ fix `cnetplot()` S3 generic/method consistency warnings (2026-01-14, Wed)\n+ fix `treeplot()` column selection bug when color variable equals size variable (2026-01-14, Wed)\n+ fix `fortify.compareClusterResult()` warnings about missing imports and global variables (2026-01-14, Wed)\n+ remove `plyr` and use `dplyr` in `method-fortify.R` (2026-01-14, Wed)\n+ fixed `treeplot()` issue where `pairwise_termsim()` with method=\"JC\" produced unnamed similarity matrix, causing \"undefined column selected\" error (2025-01-14)\n+ fixed `fortify.compareClusterResult()` warning \"NAs introduced by coercion\" when Cluster names are not numeric (2025-01-14)\n+ bug fixed in `barplot()` as `fortify()` generic in `ggplot2` checks for unused arguments in `...` (2026-01-14, Wed)\n+ remove `categorySize` parameter in `cnetplot()` (2026-01-14, Wed)\n+ bug fixed in `goplot()` as `GOSemSim` uses cache (2026-01-13, Tue)\n  - also fix `gotbl` object not found issue (2026-01-13, Tue)\n+ re-export `geneID`, `geneInCategory` and `gseaScores` from 'enrichit' (2026-01-12, Mon)\n+ update documentation: fix typos, grammar errors and use modern markdown syntax (2026-01-12, Mon)\n+ bug fixed in `update_n()` if `showCategory` is a vector of term names (2026-01-08, Thu)\n+ avoid the \"condition has length > 1\" error in `outer()` by using `Vectorize()` (2026-01-08, Thu)\n\n# enrichplot 1.31.3\n\n+ use 'enrichit' package (2025-12-07, Sun)\n+ optimize source code (2025-12-02, Tue)\n+ error handling functions imported from 'yulab.utils' (2025-12-01, Mon)\n\n# enrichplot 1.31.2\n\n+ add 'fc_threshold' parameter to `cnetplot` (2025-11-30, Sun, #338)\n  - requires 'ggtangle' v>= 0.0.9\n+ update all line width aes mapping from 'size' to 'linewidth' (2025-11-30, Sun)\n+ add 'node_label_size' parameter for `emapplot` (2025-11-30, Sun)\n+ remove `emapplot` parameters, 'group', 'group_style' and 'label_group_style' (#339) \n+ add 'showTop' parameter to limit number of genes shown in `heatplot()` and distinguish tip point size variable for `treeplot()` through internal parameter `size_var` (2025-11-23, Sat, #335) \n\n# enrichplot 1.31.1\n\n+ import `ggfun::%<+%` (2025-11-18, Tue)\n+ update `ssplot()`, `treeplot()` and `get_wordcloud()` (2025-11-15, Sat)\n+ change `set_enrichplot_color(transform = 'identity')` as default behavior (2025-11-11, Tue)\n  - now it only sets the color scale without changing the transform method\n  - explicitly set `transform = 'log10'` in `dotplot`\n+ use 'quarto' as vignette engine (2025-11-11, Tue)\n+ use `set_enrichplot_color(transform = 'identity')` in `heatplot` (2025-11-11, Tue)\n+ use `set_enrichplot_color(transform = 'identity')` in `cnetplot` (2025-11-05, Wed)\n\n# enrichplot 1.30.0\n\n+ Bioconductor RELEASE_3_22 (2025-11-01, Sat)\n\n# enrichplot 1.29.4\n\n+ remove deprecated `aes_string`/`aes_` (2025-10-23, Thu, #332)\n\n# enrichplot 1.29.3\n\n+ bug fixed of `cnetplot` for `CompareClusterResult` (2025-09-13, Sat, #329)\n  - color gene according to the gene cluster info\n+ bug fixed in pie scale label (2025-07-14, Mon, #328)\n\n# enrichplot 1.29.2\n\n+ update `treeplot` with two parameters, `leave_fontsize` and `clade_fontsize` (2025-07-12, Sat, #324, #325)\n  - remove the `fontsize` parameter as it only works for `clade_fontsize`\n+ 'log10' transform for pvalue color scale by default (2025-07-12, Sat, #316)\n+ introduce new parameters in `gseaplot2()` (2025-07-12, Sat)\n  - `pvalue_table_columns`\n  - `pvalue_table_rownames`\n  - <https://github.com/YuLab-SMU/clusterProfiler/issues/774>\n  \n# enrichplot 1.29.1\n\n+ throw error in `goplot()` if ontology is not one of the 'MF', 'CC' or 'BP' (2025-04-28, Mon, clusterProfiler#768)\n\n# enrichplot 1.28.0\n\n+ Bioconductor RELEASE_3_21 (2025-04-17, Thu)\n\n# enrichplot 1.27.5\n\n+ able to scale pie size for 'compareClusterResult' (2025-03-11, Tue, #308, #311)\n\n# enrichplot 1.27.4\n\n+ adjust pie size and category label position in `cnetplot()` (2025-01-08, Wed, #306)\n+ clean up code (2024-12-20, Fri)\n\n# enrichplot 1.27.3\n\n+ scale pies and add pie legend in `emapplot()` (2024-12-12, Thu, #304)\n+ a safe way to extract gene sets in `ridgeplot()` (2024-12-12, Thu, #303)\n\n# enrichplot 1.27.2\n\n+ `emapplot()` now allows passing color to a specific color, e.g., color = \"black\" (2024-11-29, Fri, #300)\n+ bug fixed in `emapplot()` \n  - `size_category` now works for pie node (2024-11-29, Fri, #301)\n  - legend of term nodes will be retained when `group = TRUE` (2024-11-29, Fri, #300)\n+ supports passing ID to 'showCategory' in `ridgeplot()` (2024-11-06, Wed, #295)\n+ enhancement of `cnetplot()` (2024-11-06, Wed)\n  - 'node_label' can be a vector of selected items/genes to specify the items to be displayed (#293)\n  - 'node_label' can be 'exclusive' to label genes that are uniquely belongs to categories (#253)\n  - 'node_label' can be 'share' to label genes that are share between categories (#253)\n  - 'node_label' can be, e.g. '> 1' or '< 1', to label genes that have log2FC values larger or smaller than the threshold (#253) \n  - supports using `ggtangle::geom_cnet_label()` to label items/genes in independent layer (#194, #266, #267)\n+ fixed `ridgeplot()` when selecting a specific gene set and plotting non-core genes (2024-11-06, Wed, #298)\n\n# enrichplot 1.27.1\n\n+ add 'ID' parameter in `goplot()` (2024-10-30, Wed)\n  - <https://github.com/YuLab-SMU/enrichplot/issues/292#issuecomment-2445788948>\n\n# enrichplot 1.26.0\n\n+ Bioconductor RELEASE_3_20 (2024-10-30, Wed)\n\n# enrichplot 1.25.6\n\n+ pretty gene count legend (2024-10-29, Tue, #271)\n\n# enrichplot 1.25.5\n\n+ new `emaplot()`, `goplot()`, `cnetplot()` and `ssplot()`, all power by 'ggtangle' package (2024-10-24, Thu)\n+ re-export `ggtangle::cnetplot()` (2024-10-24, Thu)\n+ remove `drag_network()` (2024-10-24, Thu)\n\n# enrichplot 1.25.4\n\n+ fixed `goplot()` (2024-10-23, Wed, #297, #732, #718)\n\n# enrichplot 1.25.3\n\n+ `hplot()`: Horizontal plot for GSEA result (2024-08-27, Tue)\n\n# enrichplot 1.25.2\n\n+ fixed bug in `ridgeplot()` (2024-08-19, Mon, clusterProfiler#704)\n\n# enrichplot 1.25.1\n\n+ fixed GeneRatio in dotplot as character of fraction issue (2024-08-16, Fri, clusterProfiler#715)\n+ use `yulab.utils::yulab_msg()` for startup message (2024-07-26, Fri)\n+ `dotplot2` to compare two selected clusters in 'compareClusterResult' object (2024-06-15, Sat)\n+ `volplot` to visualize ORA result using volcano plot (2024-06-13, Thu)\n\n# enrichplot 1.24.0\n\n+ Bioconductor RELEASE_3_19 (2024-05-15, Wed)\n\n# enrichplot 1.23.2\n\n+ separate the JC similarity method (2023-12-11, Mon, #265)\n+ fix the issue in `ridgeplot(showCategory)` : support a vector of Description, not ID(2023-12-1, Fri, #193)\n\n# enrichplot 1.23.1\n\n+ `ridgeplot()` supports passing a vector of selected pathways via the 'showCategory' parameter (2023-11-30, Thu, #193)\n+ fix `treeplot()` to compatible with the current version of ggtree and ggtreeExtra. (2023-10-28, Sat)\n+ add clusterPanel.params[[\"colnames_angle\"]] parameter to set the angle of colnames. (2023-10-28, Sat)\n\n# enrichplot 1.22.0\n\n+ Bioconductor RELEASE_3_18 (2023-10-25, Wed)\n\n# enrichplot 1.21.3\n\n+ `set_enrichplot_color()`, a helper function to set colors (2023-09-13, Wed)\n  - change default color: from c(\"red\", \"blue\") to c(\"#e06663\", \"#327eba\")\n+ use `check_installed()` to check package dependency (2023-09-08, Fri, #254)\n\n# enrichplot 1.21.2\n\n+ introduce 'facet' parameter in `dotplot()` method for `compareClusterResult`. If `facet = \"intersect\"`, the dots will be separated by enriched pathway intersection among clusters. It can set to other variable that can be used for splitting the figure (e.g., \"category\" for KEGG results) (2023-08-21, Mon)\n\n# enrichplot 1.21.1\n\n+ fixed `cnetplot.compareClusterResult()` for only contains one cluster (2023-05-24, Wed, #243)\n\n# enrichplot 1.20.0\n\n+ Bioconductor RELEASE_3_17 (2023-05-03, Wed)\n\n# enrichplot 1.19.2\n\n+ fix `emapplot()` for parameter mismatch (2023-02-20, Mon)\n+ fix `ridgeplot` for error when x@readable == TRUE and length(x@gene2Symbol) = 0 (2022-12-5, Mon)\n+ fix `ridgeplot` for error when `x@readable == TRUE` and `length(x@gene2Symbol) = 0` (2022-12-5, Mon, #217)\n\n# enrichplot 1.19.1\n\n+ fix `cnetplot()` for `node_label` parameter is flipped(2022-12-04, Sun, #216)\n+ bug fixed in `treeplot()`  (2022-11-18, Fri) \n+ enable `dotplot()` and `autofacet()` for `gseaResultList` object\n\n# enrichplot 1.18.0\n\n+ Bioconductor RELEASE_3_16 (2022-11-02, Wed)\n\n# enrichplot 1.17.4\n\n+ rename parameters of `emapplot()`, `centplot()` and  `treeplot()` (2022-09-11, Sun)\n\n# enrichplot 1.17.3\n\n+ align the dots in `treeplot()` (2022-10-1, Sat)\n+ fix a bug in color legend of `treeplot()` (2022-10-1, Sat)\n\n# enrichplot 1.17.2\n\n+ `autofacet` to automatically split `barplot` and `dotplot` into several facets (2022-09-06, Tue)\n+ `dotplot` method for `enrichResultList` object \n+ add parameters `hilight_category`, `alpha_hilight`, `alpha_nohilight` for `cnetplot()` and `emapplot` (2022-09-4, Sun)\n+ change round digits of cnetplot scatterpie legend to 1 (2022_8_29, Mon).\n+ `gsearank()` can export result as a table when `output = \"table\"` (2022-08-29, Mon, #184)\n+ fix a bug in `fc_readable()` (2022-08-29, Mon, #189)\n+ allows passing `color=\"NES\"` to `dotplot()` for `gseaResult` object (2022-08-29, Mon, #14)\n\n# enrichplot 1.17.1\n\n+ fix a bug in https://github.com/YuLab-SMU/clusterProfiler/issues/488 (2022-08-25, Thu)\n+ support multiple gene sets in `geom_gsea_gene` layer (2022-08-25, Thu)\n+ `geom_gsea_gene` layer (2022-08-24, Wed)\n+ add parameters `symbol` and `pvalue` for `heatplot.enrichResult()` (2022-08-20, Sat)\n+ change default values of `group_category` and `node_label` in `ssplot()` (2022-07-04, Mon)\n+ update document of `ssplot()` (2022-07-04, Mon)\n+ `gseaplot()` and `gseaplot2()` return `gglist` object instead of plotting the figure (2022-05-05, Thu)\n+ fix `ridgeplot` when `x@readable = TRUE` (2022-04-30, Sat)\n\n# enrichplot 1.16.0\n\n+ Bioconductor 3.15 release\n\n# enrichplot 1.15.4\n\n+ update `treeplot`: support passing rel object to `offset` and `offset_tiplab` (2022-04-24, Sun)\n\n# enrichplot 1.15.3\n\n+ export `drag_network' (2022-03-07, Mon)\n+ update `cnetplot.enrichResult` to be supported by `drag_network`(2022-3-6, Sun)\n+ add function `drag_network` to drag the nodes of networks (2022-2-25, Fri)\n+ fix a bug in `goplot`: `goplot.gseaResult` need `setType` slot instead of `ontology` slot (2022-2-22, Tue)\n+ return `gg` object instead of print it in `dotplot.compareClusterResult()` (2022-01-05, Wed, @altairwei, #160)\n\n# enrichplot 1.15.2\n\n+ add `label_format_tiplab` and `label_format_cladelab` parameters for `treeplot`(2021-12-24, Fri)\n+ support treeplot of compareCluster(GSEA algorithm) result(2021-12-13, Mon)\n+ support visualization of compareCluster(GSEA algorithm) result(2021-12-11, Sat)\n+ support scientific notation for `gseaplot2`(2021-12-4, Sat)\n\n# enrichplot 1.15.1\n\n+ fixed R check by importing `utils`\n\n# enrichplot 1.14.0\n\n+ Bioconductor 3.14 release\n\n# enrichplot 1.13.2\n\n+ mv `ep_str_wrap` to `yulab.utils::str_wrap` (2021-10-13, Wed) \n+ adjust the order of legends for `dotplot`, `emapplot`, `cnetplot` and `treeplot`(2021-10-8, Fri)\n+ update `treeplot`: add \"dotplot\" and \"heatmap\" panels for `treeplot`(2021-9-15, Wed)\n+ update `dotplot`: enable `size` parameter applicable to other columns of compareClusterResult(2021-9-17, Fri)\n+ enable `label_format` parameter for `heatplot` (2021-09-01, Wed)\n+ add `get_ggrepel_segsize` function to set `segment.size` value for `ggrepel`(2021-08-29, Sun)\n+ update `ep_str_wrap` (2021-08-28, Sat)\n+ `cnetplot` now works with a named list (2021-08-23, Mon; clusterProfiler#362)\n\n# enrichplot 1.13.1\n\n+ use `aplot::plot_list` instead of `cowplot::plot_grid` (2021-06-13, Sun\n+ add `color_category` and `color_gene` parameters for `cnetplot`(2021-6-11, Fri)\n+ Enables `showCategory` parameter to support character input in `dotplot.compareClusterResult`(2021-6-10, Thu)\n\n# enrichplot 1.12.0\n\n+ Bioconductor 3.13 release\n\n# enrichplot 1.11.3\n\n+ add function `ssplot` for similarity space plot. (2021-4-22, Thu).\n+ Reconstruct the `emapplot` function and replace `emapplot_cluster` by `emapplot(group_category = TRUE)` \n+ fix bug in `emapplot_cluster.enrichResult` when the number of cluster is 2 (2021-2-24, Wed).\n+ fix bug in `treeplot`: The legend is not the right size (2021-2-6, Sat).\n+ fix `dotplot` for `label_format` parameter doesn't work(2021-2-3, Wed).\n+ fix bug in `gseaplot2`(2021-1-28, Thu)\n\n# enrichplot 1.11.2\n\n+ update document (2021-1-7, Thu)\n+ update `dotplot`: replace `ggsymbol::geom_symbol` with `ggstar::geom_star`(2021-1-6, Wed)\n+ add parameter `shadowtext` for three functions: `emapplot`, `emapplot_cluster` and `cnetplot`. (2021-1-5, Tue)\n+ update `dotplot`: supports the use of shapes and line colors to distinguish groups (2021-1-3, Sun)\n+ add `treeplot` function (2020-12-29, Tue)\n+ rename function `get_ww` to `get_similarity_matrix` (2020-12-29, Tue)\n+ move the `emapplot` related functions to emapplot_utilities.R\n+ fix bug in `emapplot` and `cnetplot` when enrichment result is one line (2020-12-26, Sat)\n+ fix `pairwise_termsim` for the bug of repeated filtering of `showCategory`(2020-12-23, Wed)\n+ fix `showCategory` for `cnetplot`, `emapplot`, `emapplot_cluster` when  `showCategory` is a vector of term descriptions\n\n\n# enrichplot 1.11.1\n\n+ add `orderBy` and `decreasing` parameters for `ridgeplot()` (2020-11-19, Thu)\n  - <https://github.com/YuLab-SMU/enrichplot/pull/84/>\n+ update `emapplot_cluster()` to label cluster in center by default and use `ggrepel` if setting `repel = TRUE` (2020-11-08, Mon)\n  - <https://github.com/YuLab-SMU/enrichplot/pull/81>\n+ add a `label_format` parameter to support formatting label (2020-10-28, Wed)\n  + if provided with a numeric value will simply string wrap by default\n  + if provided with a function will instead set labels = user_defined_function() within the scale function\n  + <https://github.com/YuLab-SMU/enrichplot/pull/73>\n\n# enrichplot 1.10.0\n\n+ Bioconductor 3.12 release (2020-10-28, Wed)\n\n# enrichplot 1.9.5\n\n+ fix `wordcloud_i` (2020-10-15, Thu)\n+ Remove similarity calculation from emapplot\n\n# enrichplot 1.9.4\n\n+ implement `pairwise_termsim` to calculate similarity of enriched terms (2020-10-09, Fri)\n  - <https://github.com/YuLab-SMU/enrichplot/pull/67>\n+ change parameters to be more consistent\n  - <https://github.com/YuLab-SMU/enrichplot/pull/62>\n\n# enrichplot 1.9.3\n\n+ add `node_label_size` parameter to adjust the size of node label in `emapplot` function (2020-09-18, Fri)\n\n# enrichplot 1.9.2\n\n+ add function `emapplot_cluster` (2020-09-01, Tue)\n\n\n# enrichplot 1.7.3\n\n+ update `barplot` to remove using `coord_flip()` (2020-09-10, Thu)\n+ update `cnetplot` color scale to tolerate with skewed foldchange (2020-03-13, Fri)\n  - <https://github.com/YuLab-SMU/enrichplot/pull/40>\n\n# enrichplot 1.7.1\n\n+ `cnetplot` for `compareClusterResult` (`compareCluster` output) (2019-12-02, Mon)\n+ move `barplot`, `dotplot` and `fortify` methods of `compareClusterResult` from `clusterProfiler` (2019-11-2, Sat)\n\n# enrichplot 1.6.0\n\n+ Bioconductor 3.10 release\n\n# enrichplot 1.5.2\n\n+ update `node_label` parameter in `cnetplot` to support selection of subset to be labeled (2019-09-27, Fri)\n  - <https://yulab-smu.github.io/clusterProfiler-book/chapter12.html#fig:cnetNodeLabel>\n+ `upsetplot` for `gseaResult` (2019-09-25, Wed)\n+ reimplement `upsetplot` based on `ggupset` \n\n# enrichplot 1.5.1\n\n+ `gseadist` for plotting logFC distribution of selected gene sets. (2019-06-25, Tue)\n\n# enrichplot 1.4.0\n\n+ Bioconductor 3.9 release\n\n# enrichplot 1.3.2\n\n+ `dotplot` supports setting `x` to other variable, e.g. NES (2019-01-10, Thu)\n+ mv vignette to [clusterProfiler-book](https://yulab-smu.github.io/clusterProfiler-book/).\n\n# enrichplot 1.2.0\n\n+ Bioconductor 3.8 release\n\n# enrichplot 1.1.5\n\n+ `gsearank` for plotting ranked list of genes belong to specific gene set\n  (2018-07-04, Wed)\n\n# enrichplot 1.1.4\n\n+ `base_size` parameter in `gseaplot2` (2018-06-21, Thu)\n\n# enrichplot 1.1.3\n\n+ `pmcplot` for plotting pubmed trend (2018-06-14, Thu)\n+ `ggtable` for plotting table\n+ `gseaplot2` now accepts a vector of `geneSetID` (2018-06-13, Wed)\n\n# enrichplot 1.1.2\n\n+ `emapplot` supports `showCategory` parameter to accept a vector of\n`Description`  (2018-05-29, Tue)\n+ bug fixed of `showCategory` parameter for vector of `Description` in\n  `cnetplot`\n  - <https://support.bioconductor.org/p/109438/#109451>\n+ `gseaplot2` that mimic the figure generated by broad institute's GSEA software\n  (2018-05-28, Mon)\n\n# enrichplot 1.1.1\n\n+ `cnetplot` supports `showCategory` parameter to accept a vector of\n`Description`\n  - <https://github.com/GuangchuangYu/DOSE/issues/20#issuecomment-391802809>\n\n# enrichplot 1.0.0\n\n+ Bioconductor 3.7 release\n\n# enrichplot 0.99.14\n\n+ `node_label = TRUE` parameter in `cnetplot` (2018-04-08, Sun\n)\n+ drop NA in `dotplot` <2018-03-19, Mon>\n  - <https://twitter.com/S_Canchi/status/974440351162294272>\n+ enable using formula to specify x axis in `dotplot`\n\n# enrichplot 0.99.13\n\n+ fixed `goplot` issue by imporint `ggraph` <2018-03-12, Mon>\n  - <https://github.com/GuangchuangYu/enrichplot/issues/5>\n\n  - >Error in grid.Call(C_convert, x, as.integer(whatfrom), as.integer(whatto),  :\n  >invalid line type\n+ `dotplot` now supports `orderBy` and `decreasing` parameters to specify the order of dots by `order(x[[orderBy]], decreasing=decreasing)`\n\n\n# enrichplot 0.99.9\n\n+ defined `upsetplot` (2018-01-30, Tue)\n+ all visualization methods were defined as `S4` methods (2018-01-29, Mon)\n\n# enrichplot 0.99.5\n\n+ defined all visualization functions as generic functions (2018-01-03, Wed)\n+ add `colorEdge` parameter in `cnetplot`\n+ update docs\n\nenrichplot 0.99.3\n------------------------\n + import `ggplot2::rel` to fix R check (2017-11-28, Tue)\n\nenrichplot 0.99.0\n------------------------\n + ready to submit to Bioconductor (2017-11-28, Tue)\n\nenrichplot 0.0.3\n------------------------\n + `heatplot` and `gseaplot` (2017-11-28, Tue)\n + `ridgeplot`, `barplot` and `dotplot` derived from `DOSE` (2017-11-28, Tue)\n + `cnetplot` (2017-11-28, Tue)\n\nenrichplot 0.0.2\n------------------------\n + vignette added (2017-11-28, Tue)\n + `goplot` for plotting induced GO DAG (2017-11-27, Mon)\n\nenrichplot 0.0.1\n------------------------\n + `emapplot` for plotting enrichment map (2017-11-23)\n"
  },
  {
    "path": "R/00-AllClasses.R",
    "content": "#' @importFrom methods setOldClass\nsetOldClass(\"enrichResultList\")\nsetOldClass(\"gseaResultList\")\n"
  },
  {
    "path": "R/AllGenerics.R",
    "content": "#' Dot plot for enrichment result\n#'\n#'\n#' @title dotplot\n#' @rdname dotplot\n#' @param object input object.\n#' @param ... additional parameters.\n#' @return plot.\n#' @importFrom methods setGeneric\n#' @export\n#' @examples\n#' \\dontrun{\n#'     library(DOSE)\n#'     data(geneList)\n#'     de <- names(geneList)[1:100]\n#'     x <- enrichDO(de)\n#'     dotplot(x)\n#'     # use `showCategory` to select the displayed terms. It can be a number of a vector of terms.\n#'     dotplot(x, showCategory = 10)\n#'     categories <- c(\"pre-malignant neoplasm\", \"intestinal disease\",\n#'                    \"breast ductal carcinoma\", \"non-small cell lung carcinoma\")\n#'     dotplot(x, showCategory = categories)\n#'     # It can also graph compareClusterResult\n#'     data(gcSample)\n#'     library(clusterProfiler)\n#'     library(DOSE)\n#'     library(org.Hs.eg.db)\n#'     data(gcSample)\n#'     xx <- compareCluster(gcSample, fun=\"enrichGO\", OrgDb=\"org.Hs.eg.db\")\n#'     xx2 <- pairwise_termsim(xx)\n#'     library(ggstar)\n#'     dotplot(xx2)\n#'     dotplot(xx2, shape = TRUE)\n#'     dotplot(xx2, group = TRUE)\n#'     dotplot(xx2, x = \"GeneRatio\", group = TRUE, size = \"count\")\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\"dotplot\", function(object, ...) {\n    standardGeneric(\"dotplot\")\n})\n\n#' Shared term-plot parameters\n#'\n#' @name enrichplot-term-params\n#' @param showCategory number of categories to display, or a vector of terms.\n#' @param color variable used to color enriched terms, e.g. `'pvalue'`,\n#'   `'p.adjust'`, or `'qvalue'`.\n#' @param label_format a numeric wrap width, or a custom function to format\n#'   axis labels.\n#' @keywords internal\nNULL\n\n#' Shared parameters for enrichment plots\n#'\n#' @name enrichplot-common-params\n#' @param color variable used to color enriched terms, e.g. `'pvalue'`,\n#'   `'p.adjust'`, or `'qvalue'`.\n#' @param showCategory number of categories to display, or a vector of terms.\n#' @param size variable used to scale category size, one of `\"geneRatio\"`,\n#'   `\"Percentage\"`, or `\"count\"`.\n#' @param split apply `showCategory` to each category specified by `split`,\n#'   e.g., `\"ONTOLOGY\"`, `\"category\"`, or `\"intersect\"`. Default is `NULL`.\n#' @param font.size font size.\n#' @param title figure title.\n#' @param label_format a numeric wrap width, or a custom function to format\n#'   axis labels.\n#' @param includeAll logical value.\n#' @keywords internal\nNULL\n\n#' Enrichment Map for enrichment result of\n#' over-representation test or gene set enrichment analysis\n#'\n#'\n#' This function visualizes gene sets as a network (i.e. enrichment map).\n#' Mutually overlapping gene sets tend to cluster together, making it\n#' easier for interpretation. When the similarity between terms meets\n#' a certain threshold (default is 0.2, adjusted by parameter `min_edge`),\n#' there will be edges between terms. The stronger the similarity,\n#' the shorter and thicker the edges. The similarity between terms is\n#' obtained by the function `pairwise_termsim`. Details of the similarity\n#' calculation can be found in its documentation: [pairwise_termsim()].\n#' @title emapplot\n#' @rdname emapplot\n#' @param x Enrichment result.\n#' @param showCategory number of categories to display or a vector of terms.\n#' @param ... Additional parameters\n#' @return ggplot object\n#' @export\n#' @examples\n#' \\dontrun{\n#'     library(DOSE)\n#'     data(geneList)\n#'     de <- names(geneList)[1:100]\n#'     x <- enrichDO(de)\n#'     x2 <- pairwise_termsim(x)\n#'     emapplot(x2)\n#'     # use `layout` to change the layout of map\n#'     emapplot(x2, layout = \"star\")\n#'     # use `showCategory` to  select the displayed terms. It can be a number of a vector of terms.\n#'     emapplot(x2, showCategory = 10)\n#'     categories <- c(\"pre-malignant neoplasm\", \"intestinal disease\",\n#'                    \"breast ductal carcinoma\")\n#'     emapplot(x2, showCategory = categories)\n#'\n#'     # It can also graph compareClusterResult\n#'     library(clusterProfiler)\n#'     library(DOSE)\n#'     library(org.Hs.eg.db)\n#'     data(gcSample)\n#'     xx <- compareCluster(gcSample, fun=\"enrichGO\", OrgDb=\"org.Hs.eg.db\")\n#'     xx2 <- pairwise_termsim(xx)\n#'     emapplot(xx2)\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\"emapplot\", function(x, ...) {\n    standardGeneric(\"emapplot\")\n})\n\n\n#' Get the similarity matrix\n#'\n#'\n#' This function adds a similarity matrix to the termsim slot of the enrichment result.\n#' Users can use the `method` parameter to select the method of calculating the similarity.\n#' The Jaccard correlation coefficient (JC) is used by default, and it applies to all situations.\n#' When users want to calculate the correlation between GO terms or DO terms, they can also choose\n#' \"Resnik\", \"Lin\", \"Rel\" or \"Jiang\" (they are semantic similarity calculation methods from the 'GOSemSim' package),\n#' and at this time, the user needs to provide the `semData` parameter, which can be obtained through\n#' [GOSemSim::godata()].\n#' @title pairwise_termsim\n#' @rdname pairwise_termsim\n#' @param x enrichment result.\n#' @param method method of calculating the similarity between nodes,\n#' one of \"Resnik\", \"Lin\", \"Rel\", \"Jiang\", \"Wang\", and\n#' \"JC\" (Jaccard similarity coefficient) methods.\n#' @param semData `GOSemSimDATA` object, can be obtained through\n#' `GOSemSim::godata`.\n#' @param showCategory number of enriched terms to be calculated. The default value is the number of enriched terms, or 200 if the number of enriched terms exceeds 200.\n#' @examples\n#' \\dontrun{\n#'     library(clusterProfiler)\n#'     library(org.Hs.eg.db)\n#'     library(enrichplot)\n#'     library(GOSemSim)\n#'     library(DOSE)\n#'     data(geneList)\n#'     gene <- names(geneList)[abs(geneList) > 2]\n#'     ego <- enrichGO(gene  = gene,\n#'         universe      = names(geneList),\n#'         OrgDb         = org.Hs.eg.db,\n#'         ont           = \"BP\",\n#'         pAdjustMethod = \"BH\",\n#'         pvalueCutoff  = 0.01,\n#'         qvalueCutoff  = 0.05,\n#'         readable      = TRUE)\n#'     d <- godata('org.Hs.eg.db', ont=\"BP\")\n#'     ego2 <- pairwise_termsim(ego, method=\"Wang\", semData = d)\n#'     emapplot(ego2)\n#'     emapplot_cluster(ego2)\n#'    }\nsetGeneric(\n    \"pairwise_termsim\",\n    function(x, method = \"JC\", semData = NULL, showCategory = NULL) {\n        standardGeneric(\"pairwise_termsim\")\n    }\n)\n\n#' Plot induced GO DAG of significant terms\n#'\n#'\n#' @title goplot\n#' @rdname goplot\n#' @param x enrichment result.\n#' @inheritParams enrichplot-term-params\n#' @param layout layout of the map\n#' @param geom label geom, one of 'label' or 'text'\n#' @param ... additional parameters.\n#' @return ggplot object\n#' @export\n#' @examples\n#' \\dontrun{\n#' \tlibrary(clusterProfiler)\n#'   data(geneList, package = \"DOSE\")\n#' \tde <- names(geneList)[1:100]\n#' \tyy <- enrichGO(de, 'org.Hs.eg.db', ont=\"BP\", pvalueCutoff=0.01)\n#'     goplot(yy)\n#'     goplot(yy, showCategory = 5)\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\n    \"goplot\",\n    function(\n        x,\n        showCategory = 10,\n        color = \"p.adjust\",\n        layout = \"sugiyama\",\n        geom = \"text\",\n        ...\n    ) {\n        standardGeneric(\"goplot\")\n    }\n)\n\n#' Visualize GSEA analysis results\n#'\n#' Plotting function for gseaResult\n#' @title gseaplot\n#' @rdname gseaplot\n#' @param x gseaResult object\n#' @param geneSetID geneSet ID\n#' @param by one of \"runningScore\" or \"position\"\n#' @param title plot title\n#' @param ... additional parameters\n#' @return ggplot2 object\n#' @export\n#' @examples\n#' \\donttest{\n#' library(DOSE)\n#' data(geneList)\n#' x <- gseDO(geneList)\n#' gseaplot(x, geneSetID=1)\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\"gseaplot\", function(x, geneSetID, by = \"all\", title = \"\", ...) {\n    standardGeneric(\"gseaplot\")\n})\n\n\n#' Heatmap-like plot for functional classification\n#'\n#'\n#' @title heatplot\n#' @rdname heatplot\n#' @param x enrichment result.\n#' @param showCategory number of enriched terms to display\n#' @param foldChange fold change.\n#' @param label_format a numeric value setting the wrap length, alternatively a\n#' custom function to format axis labels.\n#' @param ... Additional parameters\n#' @export\n#' @return ggplot object\n#' @examples\n#' library(DOSE)\n#' data(geneList)\n#' de <- names(geneList)[1:100]\n#' x <- enrichDO(de)\n#' heatplot(x)\n#' @author Guangchuang Yu\nsetGeneric(\"heatplot\", function(x, showCategory = 30, ...) {\n    standardGeneric(\"heatplot\")\n})\n\n#' Volcano plot for enrichment result\n#'\n#'\n#' @title volplot\n#' @rdname volplot\n#' @param x enrichment result.\n#' @param color selected variable to color the dots\n#' @param xintercept value to set x-intercept\n#' @param yintercept value to set y-intercept\n#' @param showCategory number of most significant enriched terms or selected terms to\n#'     display determined by the variable selected to color the dots\n#' @param label_format a numeric value setting the wrap length, alternatively a\n#'     custom function to format axis labels.\n#' @param ... Additional parameters\n#' @export\n#' @return ggplot object\n#' @examples\n#' library(DOSE)\n#' data(geneList)\n#' de <- names(geneList)[1:100]\n#' x <- enrichDO(de)\n#' volplot(x)\n#' @author Guangchuang Yu\nsetGeneric(\n    \"volplot\",\n    function(\n        x,\n        color = \"zScore\",\n        xintercept = 1,\n        yintercept = 2,\n        showCategory = 5,\n        label_format = 30,\n        ...\n    ) {\n        standardGeneric(\"volplot\")\n    }\n)\n\n#' Ridgeline plot for GSEA result\n#'\n#'\n#' @title ridgeplot\n#' @rdname ridgeplot\n#' @param x gseaResult object\n#' @param showCategory number of categories to display or a vector of terms.\n#' @param fill one of \"pvalue\", \"p.adjust\", \"qvalue\"\n#' @param core_enrichment whether to use only core_enriched genes\n#' @param label_format a numeric value setting the wrap length, alternatively a\n#' custom function to format axis labels.\n#' @param ... additional parameters.\n#' @return ggplot object\n#' @export\n#' @examples\n#' \\donttest{\n#' library(DOSE)\n#' data(geneList)\n#' x <- gseDO(geneList)\n#' ridgeplot(x)\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\n    \"ridgeplot\",\n    function(\n        x,\n        showCategory = 30,\n        fill = \"p.adjust\",\n        core_enrichment = TRUE,\n        label_format = 30,\n        ...\n    ) {\n        standardGeneric(\"ridgeplot\")\n    }\n)\n\n\n#' upsetplot method generics\n#'\n#'\n#' @docType methods\n#' @name upsetplot\n#' @rdname upsetplot-methods\n#' @title upsetplot method\n#' @param x object\n#' @param ... additional parameters\n#' @return plot\n#' @export\n#' @author Guangchuang Yu\nsetGeneric(\"upsetplot\", function(x, ...) standardGeneric(\"upsetplot\"))\n\n\n#' Functional grouping tree diagram for enrichment result of\n#' over-representation test or gene set enrichment analysis.\n#'\n#'\n#' This function visualizes gene sets as a tree.\n#' Gene sets with high similarity tend to cluster together, making it easier\n#' for interpretation.\n#' @title treeplot\n#' @rdname treeplot\n#' @param x enrichment result.\n#' @param showCategory number of enriched terms to display\n#' @param color variable used to color enriched terms, e.g. pvalue,\n#' p.adjust or qvalue\n#' @param label_format a numeric value setting the wrap length, alternatively a\n#' custom function to format axis labels.\n#' @param ... additional parameters\n#' @return ggplot object\n#' @export\n#' @examples\n#' \\dontrun{\n#'     library(clusterProfiler)\n#'     library(org.Hs.eg.db)\n#'     library(enrichplot)\n#'     library(GOSemSim)\n#'     library(ggplot2)\n#'     library(DOSE)\n#'     data(geneList)\n#'     gene <- names(geneList)[abs(geneList) > 2]\n#'     ego <- enrichGO(gene  = gene,\n#'         universe      = names(geneList),\n#'         OrgDb         = org.Hs.eg.db,\n#'         ont           = \"BP\",\n#'         pAdjustMethod = \"BH\",\n#'         pvalueCutoff  = 0.01,\n#'         qvalueCutoff  = 0.05,\n#'         readable      = TRUE)\n#'     d <- godata('org.Hs.eg.db', ont=\"BP\")\n#'     ego2 <- pairwise_termsim(ego, method = \"Wang\", semData = d)\n#'     treeplot(ego2, showCategory = 30)\n#'     # use `hilight = FALSE` to remove ggtree::geom_hilight() layer.\n#'     treeplot(ego2, showCategory = 30, hilight = FALSE)\n#'     # use `offset` parameter to adjust the distance of bar and tree.\n#'     treeplot(ego2, showCategory = 30, hilight = FALSE, offset = rel(1.5))\n#'     # use `offset_tiplab` parameter to adjust the distance of nodes and branches.\n#'     treeplot(ego2, showCategory = 30, hilight = FALSE, offset_tiplab = rel(1.5))\n#'     keep <- rownames(ego2@termsim)[c(1:10, 16:20)]\n#'     keep\n#'     treeplot(ego2, showCategory = keep)\n#'     treeplot(ego2, showCategory = 20,\n#'         group_color = c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\"))\n#'     # It can also graph compareClusterResult\n#'     data(gcSample)\n#'     xx <- compareCluster(gcSample, fun=\"enrichKEGG\",\n#'                          organism=\"hsa\", pvalueCutoff=0.05)\n#'     xx <- pairwise_termsim(xx)\n#'     treeplot(xx)\n#'\n#'     # use `geneClusterPanel` to change the gene cluster panel.\n#'     treeplot(xx, geneClusterPanel = \"dotplot\")\n#'\n#'     treeplot(xx, geneClusterPanel = \"pie\")\n#'    }\nsetGeneric(\"treeplot\", function(x, ...) {\n    standardGeneric(\"treeplot\")\n})\n\n#' Similarity Space Plot for enrichment analysis\n#'\n#' Creates 2D visualization of enrichment results using dimension reduction\n#' techniques to show relationships between terms based on similarity.\n#'\n#' @title ssplot\n#' @rdname ssplot\n#' @inheritParams emapplot\n#' @return ggplot object\n#' @export\n#' @examples\n#' \\dontrun{\n#'     library(clusterProfiler)\n#'     library(org.Hs.eg.db)\n#'     library(enrichplot)\n#'     library(GOSemSim)\n#'     library(DOSE)\n#'     data(geneList)\n#'     gene <- names(geneList)[abs(geneList) > 2]\n#'     ego <- enrichGO(gene  = gene,\n#'         universe      = names(geneList),\n#'         OrgDb         = org.Hs.eg.db,\n#'         ont           = \"BP\",\n#'         pAdjustMethod = \"BH\",\n#'         pvalueCutoff  = 0.01,\n#'         qvalueCutoff  = 0.05,\n#'         readable      = TRUE)\n#'     d <- godata('org.Hs.eg.db', ont=\"BP\")\n#'     ego2 <- pairwise_termsim(ego, method = \"Wang\", semData = d)\n#'     ssplot(ego2)\n#' }\n#' @author Guangchuang Yu\nsetGeneric(\"ssplot\", function(x, ...) {\n    standardGeneric(\"ssplot\")\n})\n\n#' Manhattan plot for enrichment result\n#'\n#' @title manhattanplot\n#' @rdname manhattanplot\n#' @param x enrichment result.\n#' @inheritParams enrichplot-common-params\n#' @param ... additional parameters.\n#' @return ggplot object\n#' @export\nsetGeneric(\"manhattanplot\", function(x, ...) {\n    standardGeneric(\"manhattanplot\")\n})\n"
  },
  {
    "path": "R/barplot.R",
    "content": "#' Barplot of enrichResult\n#'\n#' Barplot of enrichResult\n#'\n#' @importFrom graphics barplot\n#' @importFrom ggplot2 %+%\n#' @importFrom ggplot2 scale_fill_continuous\n#' @importFrom ggplot2 aes\n#' @importFrom ggplot2 geom_col\n#' @importFrom ggplot2 theme\n#' @importFrom ggplot2 ggtitle\n#' @importFrom ggplot2 xlab\n#' @importFrom ggplot2 ylab\n#' @importFrom ggplot2 scale_y_discrete\n#' @title barplot\n#' @param height enrichResult object\n#' @param x one of 'Count' and 'GeneRatio'\n#' @param color one of 'pvalue', 'p.adjust' and 'qvalue'\n#' @param showCategory number of categories to display or a vector of terms.\n#' @param font.size font size\n#' @param title plot title\n#' @param label_format a numeric value sets wrap length, alternatively a\n#' custom function to format axis labels.\n#' by default wraps names longer than 30 characters\n#' @param ... additional parameters\n#' @method barplot enrichResult\n#' @export\n#' @return ggplot object\n#' @examples\n#' library(DOSE)\n#' data(geneList)\n#' de <- names(geneList)[1:100]\n#' x <- enrichDO(de)\n#' barplot(x)\n#' # use `showCategory` to select the displayed terms. It can be a number of a vector of terms.\n#' barplot(x, showCategory = 10)\n#' categories <- c(\"urinary bladder cancer\", \"bronchiolitis obliterans\",\n#'                \"aortic aneurysm\", \"esophageal cancer\")\n#' barplot(x, showCategory = categories)\nbarplot.enrichResult <- function(\n    height,\n    x = \"Count\",\n    color = 'p.adjust',\n    showCategory = 8,\n    font.size = 12,\n    title = \"\",\n    label_format = 30,\n    ...\n) {\n    ## use *height* to satisy barplot generic definition\n    ## actually here is an enrichResult object.\n    object <- height\n\n    colorBy <- match.arg(color, c(\"pvalue\", \"p.adjust\", \"qvalue\"))\n    if (x == \"geneRatio\" || x == \"GeneRatio\") {\n        x <- \"GeneRatio\"\n    } else if (x == \"count\" || x == \"Count\") {\n        x <- \"Count\"\n    }\n\n    #df <- fortify(object, showCategory = showCategory, by = x, ...)\n    dots <- list(...)\n    supported_params <- c(\"order\", \"drop\", \"split\")\n    fortify_params <- dots[names(dots) %in% supported_params]\n\n    # Create the call to fortify without passing ... directly\n    # This prevents ggplot2 from checking for unused parameters\n    fortify_args <- list(\n        model = object,\n        showCategory = showCategory,\n        by = x\n    )\n\n    # Add supported parameters explicitly\n    if (\"order\" %in% names(fortify_params)) {\n        fortify_args$order <- fortify_params$order\n    }\n    if (\"drop\" %in% names(fortify_params)) {\n        fortify_args$drop <- fortify_params$drop\n    }\n    if (\"split\" %in% names(fortify_params)) {\n        fortify_args$split <- fortify_params$split\n    }\n\n    # Use do.call to avoid passing ... through function calls\n    df <- do.call(fortify.enrichResult, fortify_args)\n\n    if (colorBy %in% colnames(df)) {\n        p <- ggplot(\n            df,\n            aes(\n                x = .data[[x]],\n                y = .data[[\"Description\"]],\n                fill = .data[[colorBy]]\n            )\n        ) +\n            theme_dose(font.size) +\n            set_enrichplot_color(type = \"fill\", name = color)\n    } else {\n        p <- ggplot(\n            df,\n            aes(\n                x = .data[[x]],\n                y = .data[[\"Description\"]],\n                fill = .data[[\"Description\"]]\n            )\n        ) +\n            theme_dose(font.size) +\n            theme(legend.position = \"none\")\n    }\n\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n\n    p +\n        geom_col() + # geom_bar(stat = \"identity\") + coord_flip() +\n        scale_y_discrete(labels = label_func) +\n        ggtitle(title) +\n        ylab(NULL) # + xlab(NULL)\n}\n\n#' @method barplot compareClusterResult\n#' @export\nbarplot.compareClusterResult <- function(\n    height,\n    color = \"p.adjust\",\n    showCategory = 5,\n    by = \"geneRatio\",\n    includeAll = TRUE,\n    font.size = 12,\n    title = \"\",\n    ...\n) {\n    ## use *height* to satisy barplot generic definition\n    ## actually here is an compareClusterResult object.\n    df <- fortify(\n        height,\n        showCategory = showCategory,\n        by = by,\n        includeAll = includeAll\n    )\n    plotting.clusterProfile(\n        df,\n        type = \"bar\",\n        colorBy = color,\n        by = by,\n        title = title,\n        font.size = font.size\n    )\n}\n"
  },
  {
    "path": "R/cnetplot.R",
    "content": "#' Category-Gene-Network Plot\n#'\n#' Category-gene-network plot\n#' @rdname cnetplot\n#' @param x input object\n#' @param layout network layout\n#' @param showCategory number of categories to display or a vector of terms.\n#' @param color_category color of category nodes\n#' @param size_category relative size of the category nodes\n#' @param color_item color of item nodes\n#' @param size_item relative size of the item nodes (e.g., genes)\n#' @param color_edge color of edge\n#' @param size_edge relative size of edge\n#' @param categorySizeBy An expression (e.g., `itemNum`, `p.adjust`) or a formula\n#'   (e.g., `~ -log10(p.adjust)`) to set the category node size. For\n#'   `compareClusterResult`, this controls the category pie size.\n#' @param node_label one of 'all', 'none', 'category', 'item', 'exclusive' or 'share'.\n#' 'exclusive' labels genes that uniquely belong to categories; 'share' labels genes that are shared between categories.\n#' @param foldChange numeric values to color the item (e.g., fold change of gene expression values)\n#' @param fc_threshold threshold for filtering genes by absolute fold change (e.g., fc_threshold = 1 keeps only genes with |foldChange| > 1).\n#' @param hilight selected categories to be highlighted\n#' @param hilight_alpha transparency value for non-highlighted items\n#' @param split apply `showCategory` to each category specified by `split` for\n#'   `compareClusterResult`, e.g. `ONTOLOGY`, `category` or `intersect`.\n#' @param includeAll logical value passed to `fortify()` when selecting terms\n#'   from a `compareClusterResult`.\n#' @param ... additional parameters\n#' @importFrom ggtangle cnetplot\n#' @method cnetplot enrichResult\n#' @export\n#' @seealso\n#' [cnetplot][ggtangle::cnetplot]\ncnetplot.enrichResult <- function(\n    x,\n    layout = igraph::layout_with_kk,\n    showCategory = 5,\n    color_category = \"#E5C494\",\n    size_category = 1,\n    color_item = \"#B3B3B3\",\n    size_item = 1,\n    color_edge = \"grey\",\n    size_edge = .5,\n    categorySizeBy = ~itemNum,\n    node_label = \"all\",\n    foldChange = NULL,\n    fc_threshold = NULL,\n    hilight = \"none\",\n    hilight_alpha = .3,\n    ...\n) {\n    geneSets <- extract_geneSets(x, showCategory)\n    foldChange <- fc_readable(x, foldChange)\n\n    # Attach enrichment results to geneSets attributes\n    y <- as.data.frame(x)\n    # Filter y to match geneSets (names are Descriptions)\n    # We match by Description.\n    # Note: If duplicate Descriptions exist, this might be ambiguous,\n    # but extract_geneSets assumes Descriptions are valid keys.\n    idx <- match(names(geneSets), y$Description)\n    y_subset <- y[idx, ]\n    \n    for (col in colnames(y_subset)) {\n        if (is.numeric(y_subset[[col]])) {\n            attr(geneSets, col) <- y_subset[[col]]\n        }\n    }\n\n    args <- list(...)\n    plot_args <- list(\n        x = geneSets,\n        layout = layout,\n        showCategory = showCategory,\n        foldChange = foldChange,\n        fc_threshold = fc_threshold,\n        color_category = color_category,\n        size_category = size_category,\n        color_item = color_item,\n        size_item = size_item,\n        color_edge = color_edge,\n        size_edge = size_edge,\n        node_label = node_label,\n        hilight = hilight,\n        hilight_alpha = hilight_alpha,\n        categorySizeBy = categorySizeBy\n    )\n    \n    final_args <- c(plot_args, args)\n    \n    p <- do.call(cnetplot, final_args)\n\n    p <- p +\n        set_enrichplot_color(\n            colors = get_enrichplot_color(3),\n            name = \"fold change\",\n            transform = 'identity'\n        )\n    if (!is.null(foldChange)) {\n        p <- p +\n            guides(\n                size = guide_legend(order = 1),\n                color = guide_colorbar(order = 2)\n            )\n    }\n\n    return(p + guides(alpha = \"none\"))\n}\n\n#' @rdname cnetplot\n#' @method cnetplot gseaResult\n#' @export\ncnetplot.gseaResult <- cnetplot.enrichResult\n\n#' @rdname cnetplot\n#' @param pie one of 'equal' or 'Count' to set the slice ratio of the pies\n#' @method cnetplot compareClusterResult\n#' @export\ncnetplot.compareClusterResult <- function(\n    x,\n    layout = igraph::layout_with_kk,\n    showCategory = 5,\n    color_category = \"#E5C494\",\n    size_category = 1,\n    color_item = \"#B3B3B3\",\n    size_item = 1,\n    color_edge = \"grey\",\n    size_edge = .5,\n    categorySizeBy = ~itemNum,\n    node_label = \"all\",\n    foldChange = NULL,\n    fc_threshold = NULL,\n    hilight = \"none\",\n    hilight_alpha = .3,\n    pie = \"equal\",\n    split = NULL,\n    includeAll = TRUE,\n    ...\n) {\n    category_size_quo <- rlang::enquo(categorySizeBy)\n    d <- tidy_compareCluster(\n        x,\n        showCategory = showCategory,\n        split = split,\n        includeAll = includeAll\n    )\n    y <- split(d$geneID, d$Description)\n    gs <- lapply(y, function(item) unique(unlist(strsplit(item, split = \"/\"))))\n    category_size <- compute_comparecluster_category_size(d, category_size_quo)\n\n    p <- cnetplot(\n        gs,\n        layout = layout,\n        showCategory = names(gs),\n        foldChange = foldChange,\n        fc_threshold = fc_threshold,\n        color_category = color_category,\n        size_category = 0,\n        color_item = color_item,\n        size_item = 0,\n        color_edge = color_edge,\n        size_edge = size_edge,\n        node_label = \"none\",\n        hilight = hilight,\n        hilight_alpha = hilight_alpha,\n        ...\n    )\n\n    p <- add_node_pie(\n        p,\n        d,\n        pie,\n        category_scale = size_category,\n        item_scale = size_item,\n        category_size = category_size\n    )\n\n    p <- p + geom_cnet_label(node_label = node_label)\n\n    return(p)\n}\n\n\n#' @importFrom ggplot2 coord_fixed\nadd_node_pie <- function(\n    p,\n    d,\n    pie = \"equal\",\n    category_scale = 1,\n    item_scale = 1,\n    category_size = NULL\n) {\n    ## category nodes\n    dd <- d[, c('Cluster', 'Description', 'Count')]\n    default_size <- sapply(split(dd$Count, dd$Description), sum)\n    if (is.null(category_size)) {\n        category_size <- default_size\n    } else {\n        category_size <- category_size[names(default_size)]\n    }\n    if (pie == \"equal\") {\n        dd$Count <- 1\n    }\n    dd <- tidyr::pivot_wider(\n        dd,\n        names_from = \"Cluster\",\n        values_from = \"Count\",\n        values_fill = 0\n    )\n    normalized_category_size <- normalize_comparecluster_radius(category_size)\n    dd$pathway_radius <- normalized_category_size[dd$Description] * category_scale\n\n    ## gene nodes\n    y <- split(d$geneID, d$Cluster)\n    gs <- lapply(y, function(item) unique(unlist(strsplit(item, split = \"/\"))))\n    dg <- yulab.utils::ls2df(gs) |> setNames(c(\"Cluster\", \"Description\")) # second column is geneID\n    dg$Count <- 1\n    dg <- tidyr::pivot_wider(\n        dg,\n        names_from = \"Cluster\",\n        values_from = \"Count\",\n        values_fill = 0\n    )\n    dg$pathway_radius <- .05 * item_scale\n\n    d2 <- rbind(dd, dg)\n\n    p <- p %<+%\n        d2 +\n        scatterpie::geom_scatterpie(\n            aes(\n                x = .data$x,\n                y = .data$y,\n                r = .data$pathway_radius\n            ),\n            cols = as.character(unique(d$Cluster)),\n            legend_name = \"Cluster\",\n            color = NA\n        ) +\n        coord_fixed() +\n        guides(size = \"none\")\n\n    if (any(dd$pathway_radius > 0)) {\n        p <- p + scatterpie::geom_scatterpie_legend(\n            unique(dd$pathway_radius),\n            x = min(p$data$x),\n            y = min(p$data$y),\n            n = 3,\n            labeller = function(x) {\n                format(signif(x / category_scale * sum(category_size), 3), trim = TRUE)\n            }\n        )\n    }\n\n    return(p)\n}\n\ncompute_comparecluster_category_size <- function(d, categorySizeBy) {\n    term_names <- unique(as.character(d$Description))\n    gene_sets <- split(d$geneID, d$Description)\n    item_num <- vapply(\n        gene_sets[term_names],\n        function(item) {\n            length(unique(unlist(strsplit(item, split = \"/\"))))\n        },\n        FUN.VALUE = numeric(1)\n    )\n\n    term_df <- data.frame(\n        Description = term_names,\n        itemNum = item_num,\n        Count = vapply(\n            split(d$Count, d$Description)[term_names],\n            sum,\n            FUN.VALUE = numeric(1)\n        ),\n        stringsAsFactors = FALSE\n    )\n\n    numeric_cols <- setdiff(names(d)[vapply(d, is.numeric, logical(1))], \"Count\")\n    if (length(numeric_cols) > 0) {\n        for (col in numeric_cols) {\n            term_df[[col]] <- summarize_comparecluster_numeric_column(\n                d[[col]],\n                d$Description,\n                term_names,\n                col\n            )\n        }\n    }\n\n    if (inherits(categorySizeBy, \"quosure\")) {\n        category_size_expr <- rlang::quo_get_expr(categorySizeBy)\n        category_size_env <- rlang::quo_get_env(categorySizeBy)\n    } else {\n        category_size_expr <- substitute(categorySizeBy)\n        category_size_env <- parent.frame()\n    }\n    if (rlang::is_formula(category_size_expr)) {\n        category_size_expr <- rlang::f_rhs(category_size_expr)\n    }\n\n    category_size <- rlang::eval_tidy(\n        rlang::new_quosure(category_size_expr, env = category_size_env),\n        data = term_df\n    )\n    if (!is.numeric(category_size)) {\n        stop(\"`categorySizeBy` must evaluate to a numeric vector.\")\n    }\n    if (length(category_size) == 1) {\n        category_size <- rep(category_size, nrow(term_df))\n    }\n    if (length(category_size) != nrow(term_df)) {\n        stop(\"`categorySizeBy` must return a scalar or one value per category.\")\n    }\n    if (anyNA(category_size) || any(!is.finite(category_size))) {\n        stop(\"`categorySizeBy` returned non-finite values.\")\n    }\n    if (any(category_size < 0)) {\n        stop(\"`categorySizeBy` must be non-negative for pie radius scaling.\")\n    }\n    if (sum(category_size) <= 0) {\n        stop(\"`categorySizeBy` must produce at least one positive value.\")\n    }\n\n    stats::setNames(category_size, term_df$Description)\n}\n\nsummarize_comparecluster_numeric_column <- function(values, groups, group_names, column_name) {\n    split_values <- split(values, groups)\n    vapply(\n        split_values[group_names],\n        function(x) {\n            x <- x[is.finite(x)]\n            if (length(x) == 0) {\n                return(NA_real_)\n            }\n            if (column_name %in% c(\"pvalue\", \"p.adjust\", \"qvalue\")) {\n                return(min(x))\n            }\n            unique_values <- unique(x)\n            if (length(unique_values) == 1) {\n                return(unique_values)\n            }\n            NA_real_\n        },\n        FUN.VALUE = numeric(1)\n    )\n}\n\nnormalize_comparecluster_radius <- function(x) {\n    total <- sum(x)\n    if (!is.finite(total) || total <= 0) {\n        stop(\"Category pie size scaling requires a positive total size.\")\n    }\n    x / total\n}\n\n\ntidy_compareCluster <- function(\n    x,\n    showCategory,\n    split = NULL,\n    includeAll = TRUE\n) {\n    d <- fortify(\n        x,\n        showCategory = showCategory,\n        includeAll = includeAll,\n        split = split\n    )\n    d$Cluster <- sub(\"\\n.*\", \"\", d$Cluster)\n\n    if (\"core_enrichment\" %in% colnames(d)) {\n        ## for GSEA result\n        d$geneID <- d$core_enrichment\n    }\n    return(d)\n}\n"
  },
  {
    "path": "R/color_utils.R",
    "content": "#' Color utility functions for enrichplot package\n#'\n#' This file contains all color-related helper functions\n\n#' Get default enrichplot colors\n#'\n#' @param n number of colors (2 or 3)\n#' @return color vector\n#' @export\nget_enrichplot_color <- function(n = 2) {\n    colors <- getOption(\"enrichplot.colours\")\n    if (!is.null(colors)) {\n        return(colors)\n    }\n\n    if (n != 2 && n != 3) {\n        rlang::abort(\"'n' should be 2 or 3\", .arg = \"n\")\n    }\n\n    colors = c(\"#e06663\", \"#327eba\")\n    if (n == 2) {\n        return(colors)\n    }\n\n    if (n == 3) return(c(colors[1], \"white\", colors[2]))\n}\n\n#' Helper function to set color scale for enrichplot\n#'\n#' @param colors user provided color vector\n#' @param type one of 'color', 'colour' or 'fill'\n#' @param name name of the color legend\n#' @param .fun force to use user provided color scale function\n#' @param reverse whether reverse the color scheme\n#' @param transform transform the color scale\n#' @param ... additional parameters\n#' @return a color scale\n#' @importFrom ggplot2 scale_fill_continuous\n#' @importFrom ggplot2 scale_color_continuous\n#' @importFrom ggplot2 scale_fill_gradientn\n#' @importFrom ggplot2 scale_color_gradientn\n#' @importFrom ggplot2 guide_colorbar\n#' @importFrom yulab.utils yulab_abort\n#' @importFrom yulab.utils yulab_warn\n#' @importFrom yulab.utils check_input\n#' @author Guangchuang Yu\n#' @export\nset_enrichplot_color <- function(\n    colors = get_enrichplot_color(2),\n    type = \"color\",\n    name = NULL,\n    .fun = NULL,\n    reverse = TRUE,\n    transform = 'identity',\n    ...\n) {\n    type <- match.arg(type, c(\"color\", \"colour\", \"fill\"))\n    if (!reverse) {\n        colors = rev(colors)\n    }\n    n <- length(colors)\n    ## Input validation\n    check_input(colors, type = \"character\", min_length = 2, arg_name = \"colors\")\n    check_input(type, type = \"character\", arg_name = \"type\")\n    \n    if (n < 2) {\n        yulab_abort(\"'colors' should be of length >= 2\", class = \"color_length_error\")\n    } else if (n == 2) {\n        params <- list(low = colors[1], high = colors[2])\n        fn_suffix <- \"continuous\"\n    } else if (n == 3) {\n        params <- list(low = colors[1], mid = colors[2], high = colors[3])\n        fn_suffix <- \"gradient2\"\n    } else {\n        params <- list(colors = colors)\n        fn_suffix <- \"gradientn\"\n    }\n\n    if (!is.null(.fun)) {\n        if (n == 3) {\n            fn_type <- which_scale_fun(.fun)\n            if (fn_type == \"gradientn\") {\n                params <- list(colors = colors)\n            } else {\n                params <- list(\n                    low = colors[1],\n                    mid = colors[2], \n                    high = colors[3]\n                )\n            }\n        }\n    } else {\n        fn <- sprintf(\"scale_%s_%s\", type, fn_suffix)\n        .fun <- getFromNamespace(fn, \"ggplot2\")\n    }\n\n    params$guide <- guide_colorbar(reverse = reverse, order = 1)\n    params$name <- name\n    params$transform <- transform\n\n    params <- modifyList(params, list(...))\n\n    do.call(.fun, params)\n}\n\n#' Determine which scale function to use\n#'\n#' @param .fun function to check\n#' @return scale function type\n#' @noRd\nwhich_scale_fun <- function(.fun) {\n    params <- args(.fun) |> as.list() |> names()\n    if (\"colours\" %in% params) {\n        return(\"gradientn\")\n    }\n    if (\"mid\" %in% params) {\n        return(\"gradient2\")\n    }\n    return(\"continuous\")\n}\n\n#' Create color palette for continuous data\n#'\n#' @param colors colors of length >=2\n#' @return color vector\n#' @importFrom rlang check_installed\n#' @importFrom yulab.utils check_input\n#' @export\n#' @examples\n#' color_palette(c(\"red\", \"yellow\", \"green\"))\n#' @author guangchuang yu\ncolor_palette <- function(colors) {\n    ## Check input validity\n    yulab.utils::check_input(colors, type = \"character\", min_length = 2, arg_name = \"colors\")\n    \n    rlang::check_installed('grDevices', 'for `color_palette()`.')\n    grDevices::colorRampPalette(colors)(n = 299)\n}\n\n#' Predefined color palettes\nenrichplot_point_shape <- ggfun:::enrichplot_point_shape\nsig_palette <- color_palette(c(\"red\", \"yellow\", \"blue\"))\nheatmap_palette <- color_palette(c(\"red\", \"yellow\", \"green\"))"
  },
  {
    "path": "R/data_utils.R",
    "content": "#' Data processing utility functions for enrichplot package\n#'\n#' This file contains data manipulation and processing helper functions\n\n#' Update showCategory parameter\n#'\n#' @param x input object\n#' @param showCategory category specification\n#' @return updated category specification\n#' @noRd\nupdate_n <- function(x, showCategory) {\n    ## Input validation\n    check_input(x, arg_name = \"x\")\n    check_input(showCategory, arg_name = \"showCategory\")\n\n    if (!is.numeric(showCategory)) {\n        if (inherits(x, 'list')) {\n            showCategory <- showCategory[showCategory %in% names(x)]\n        } else {\n            if (!\"Description\" %in% colnames(as.data.frame(x))) {\n                yulab_abort(\n                    \"Input data must have 'Description' column\",\n                    class = \"missing_column_error\"\n                )\n            }\n            showCategory <- intersect(showCategory, x$Description)\n        }\n        return(showCategory)\n    }\n\n    n <- showCategory\n    if (inherits(x, 'list')) {\n        nn <- length(x)\n    } else {\n        nn <- nrow(x)\n    }\n    if (nn < n) {\n        yulab_warn(\n            paste0(\n                \"showCategory (\",\n                n,\n                \") is larger than available items (\",\n                nn,\n                \"). Using \",\n                nn\n            ),\n            class = \"showCategory_warning\"\n        )\n        n <- nn\n    }\n\n    return(n)\n}\n\n#' Extract gene sets from enrichment result\n#'\n#' @param x enrichment result object\n#' @param n number of categories or specific categories\n#' @return gene sets list\n#' @noRd\nextract_geneSets <- function(x, n) {\n    n <- update_n(x, n)\n\n    if (inherits(x, 'list')) {\n        geneSets <- x\n    } else {\n        geneSets <- geneInCategory(x) ## use core gene for gsea result\n        y <- as.data.frame(x)\n        geneSets <- geneSets[y$ID]\n        names(geneSets) <- y$Description\n    }\n    if (is.numeric(n)) {\n        return(geneSets[1:n])\n    }\n    return(geneSets[n]) ## if n is a vector of Description\n}\n\n#' Make fold change data readable\n#'\n#' @param x enrichment result object\n#' @param foldChange fold change vector\n#' @return readable fold change vector\n#' @noRd\nfc_readable <- function(x, foldChange = NULL) {\n    if (is.null(foldChange)) {\n        return(NULL)\n    }\n\n    if (x@readable && x@keytype != \"SYMBOL\") {\n        gid <- names(foldChange)\n        if (is(x, 'gseaResult')) {\n            ii <- gid %in% names(x@geneList)\n        } else {\n            ii <- gid %in% x@gene\n        }\n        gid[ii] <- x@gene2Symbol[gid[ii]]\n        names(foldChange) <- gid\n    }\n    return(foldChange)\n}\n\n#' Calculate overlap ratio between two gene sets\n#'\n#' @param x first gene set\n#' @param y second gene set\n#' @return Jaccard similarity coefficient\n#' @noRd\noverlap_ratio <- function(x, y) {\n    x <- unique(unlist(x))\n    y <- unique(unlist(y))\n    length(intersect(x, y)) / length(union(x, y))\n}\n\n#' Calculate Jaccard similarity matrix\n#'\n#' @param gsetlist list of gene sets\n#' @param id gene set IDs\n#' @param name gene set names\n#' @return similarity matrix\n#' @noRd\n.cal_jc_similarity <- function(gsetlist, id = NULL, name = NULL) {\n    if (is.null(id)) {\n        id <- names(gsetlist)\n    }\n    n <- length(id)\n    w <- matrix(NA, nrow = n, ncol = n)\n    if (is.null(name)) {\n        name <- id\n    }\n    colnames(w) <- rownames(w) <- name\n\n    # Vectorized computation: precompute all gene sets\n    gsets <- lapply(gsetlist[id], unique)\n\n    # Use outer function for vectorized computation\n    jc_matrix <- outer(seq_len(n), seq_len(n), Vectorize(function(i, j) {\n        if (i == j) {\n            return(1)\n        }\n        overlap_ratio(gsets[[i]], gsets[[j]])\n    }))\n\n    # Ensure symmetry\n    jc_matrix[lower.tri(jc_matrix)] <- t(jc_matrix)[lower.tri(t(jc_matrix))]\n\n    colnames(jc_matrix) <- rownames(jc_matrix) <- name\n\n    return(jc_matrix)\n}\n\n#' Prepare pie data for genes in cnetplot (compareClusterResult only)\n#'\n#' @param y data frame from compareClusterResult\n#' @return pie data\n#' @importFrom rlang check_installed\n#' @noRd\nprepare_pie_gene <- function(y) {\n    ## Input validation\n    check_input(y, type = \"data.frame\", arg_name = \"y\")\n\n    check_installed('tibble', 'for `prepare_pie_gene()`.')\n    gene_pie <- tibble::as_tibble(y[, c(\"Cluster\", \"Description\", \"geneID\")])\n    gene_pie$geneID <- strsplit(gene_pie$geneID, '/')\n    gene_pie2 <- as.data.frame(tidyr::unnest(gene_pie, cols = geneID))\n    gene_pie2 <- unique(gene_pie2)\n    prepare_pie_data(gene_pie2, pie = \"equal\", type = \"gene\")\n}\n\n#' Prepare pie data for categories in cnetplot/emapplot\n#'\n#' @param enrichDf enrichment data frame\n#' @param pie proportion type (equal, count, Count)\n#' @return pie data matrix\n#' @noRd\nprepare_pie_category <- function(enrichDf, pie = \"equal\") {\n    pie <- match.arg(pie, c(\"equal\", \"count\", \"Count\"))\n    if (pie == \"count\") {\n        pie <- \"Count\"\n    }\n\n    pie_data <- enrichDf[, c(\"Cluster\", \"Description\", \"Count\")]\n    pie_data[, \"Description\"] <- as.character(pie_data[, \"Description\"])\n    prepare_pie_data(pie_data, pie = pie)\n}\n\n#' Prepare pie data matrix\n#'\n#' @param pie_data input data\n#' @param pie proportion type\n#' @param type gene or category\n#' @return pie data matrix\n#' @noRd\nprepare_pie_data <- function(pie_data, pie = \"equal\", type = \"category\") {\n    if (type == \"category\") {\n        ID_unique <- unique(pie_data[, 2])\n    } else {\n        ID_unique <- unique(pie_data[, 3])\n    }\n\n    Cluster_unique <- unique(pie_data[, 1])\n    ID_Cluster_mat <- matrix(\n        0,\n        nrow = length(ID_unique),\n        ncol = length(Cluster_unique)\n    )\n    rownames(ID_Cluster_mat) <- ID_unique\n    colnames(ID_Cluster_mat) <- Cluster_unique\n    ID_Cluster_mat <- as.data.frame(ID_Cluster_mat, stringAsFactors = FALSE)\n\n    if (pie == \"Count\") {\n        # Vectorized matrix indexing\n        idx <- cbind(\n            match(pie_data[, 2], rownames(ID_Cluster_mat)),\n            match(pie_data[, 1], colnames(ID_Cluster_mat))\n        )\n        ID_Cluster_mat[idx] <- pie_data[, 3]\n        # Convert all columns to numeric at once\n        ID_Cluster_mat[] <- lapply(ID_Cluster_mat, as.numeric)\n        return(ID_Cluster_mat)\n    }\n\n    # Vectorized matrix indexing for equal pie\n    if (type == \"category\") {\n        idx <- cbind(\n            match(pie_data[, 2], rownames(ID_Cluster_mat)),\n            match(pie_data[, 1], colnames(ID_Cluster_mat))\n        )\n    } else {\n        idx <- cbind(\n            match(pie_data[, 3], rownames(ID_Cluster_mat)),\n            match(pie_data[, 1], colnames(ID_Cluster_mat))\n        )\n    }\n    ID_Cluster_mat[idx] <- 1\n    return(ID_Cluster_mat)\n}\n\n#' Convert compareClusterResult to data frame\n#'\n#' @param x compareClusterResult object\n#' @param ... additional parameters\n#' @return data frame\n#' @export\n#' @method as.data.frame compareClusterResult\nas.data.frame.compareClusterResult <- function(x, ...) {\n    as.data.frame(x@compareClusterResult, ...)\n}\n\n\n\n"
  },
  {
    "path": "R/densityplot.R",
    "content": "#' plot logFC distribution of selected gene sets\n#'\n#' \n#' @title gseadist \n#' @param x GSEA result\n#' @param IDs gene set IDs\n#' @param type one of 'density' or 'boxplot'\n#' @return distribution plot\n#' @importFrom ggplot2 geom_density\n#' @importFrom ggplot2 geom_boxplot\n#' @export\n#' @author Guangchuang Yu\ngseadist <- function(x, IDs, type =  'density') {\n    d <- data.frame(gene = names(x@geneList),\n                    logFC = x@geneList,\n                    category = 'All Genes')\n\n    ds <- do.call('rbind', lapply(IDs, function(i) {\n        if (!is.numeric(i)) {\n            i <- match(i, x$ID)\n            if (is.na(i))\n                i <- match(i,  x$Description)\n        } \n        id <- x$ID[i]\n\n        gene <- x@geneSets[[id]]\n        gs <- x@geneList[gene]\n        gs <- gs[!is.na(gs)]\n        data.frame(gene = names(gs),\n                   logFC = gs,\n                   category = x$Description[i])\n    }))\n    dd <- rbind(d, ds)\n\n    p <- ggplot(dd) + theme_minimal()\n\n    if (type == 'density') {\n        p <- p + \n            geom_density(aes(x = .data$logFC, color = .data$category)) +\n            ## geom_rug(data = ds, show.legend = FALSE) +\n            ylab(NULL) +\n            theme(legend.title = element_blank(),\n                  legend.position = 'bottom')\n    } else if (type == 'boxplot') {\n        p <- p +\n            geom_boxplot(aes(x = .data$category, y = .data$logFC, fill = .data$category))  +\n            xlab(NULL) +\n            theme(legend.position = 'none')\n    } \n    return(p)\n}\n"
  },
  {
    "path": "R/dotplot.R",
    "content": "#' @rdname dotplot\n#' @exportMethod dotplot\n#' @author Guangchuang Yu\nsetMethod(\n    \"dotplot\",\n    signature(object = \"enrichResult\"),\n    function(\n        object,\n        x = \"GeneRatio\",\n        color = \"p.adjust\",\n        showCategory = 10,\n        size = NULL,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        orderBy = \"x\",\n        label_format = 30,\n        ...\n    ) {\n        dotplot.enrichResult(\n            object = object,\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            orderBy = orderBy,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname dotplot\n#' @exportMethod dotplot\nsetMethod(\n    \"dotplot\",\n    signature(object = \"gseaResult\"),\n    function(\n        object,\n        x = \"GeneRatio\",\n        color = \"p.adjust\",\n        showCategory = 10,\n        size = NULL,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        orderBy = \"x\",\n        label_format = 30,\n        ...\n    ) {\n        if (color == \"NES\") {\n            NES <- TRUE\n            color <- \"p.adjust\"\n        } else {\n            NES <- FALSE\n        }\n        p <- dotplot.enrichResult(\n            object = object,\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            orderBy = orderBy,\n            label_format = label_format,\n            ...\n        )\n\n        if (NES) {\n            p <- suppressMessages(\n                p +\n                    aes(fill = .data$NES) +\n                    set_enrichplot_color(\n                        type = \"fill\",\n                        name = \"NES\"\n                    )\n            )\n        }\n        return(p)\n    }\n)\n\n#' @rdname dotplot\n#' @aliases dotplot,compareClusterResult,ANY-method\n#' @exportMethod dotplot\nsetMethod(\n    \"dotplot\",\n    signature(object = \"compareClusterResult\"),\n    function(\n        object,\n        x = \"Cluster\",\n        color = \"p.adjust\",\n        showCategory = 5,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        by = \"geneRatio\",\n        size = NULL,\n        includeAll = TRUE,\n        label_format = 30,\n        ...\n    ) {\n        dotplot.compareClusterResult(\n            object,\n            x = x,\n            colorBy = color,\n            showCategory = showCategory,\n            by = by,\n            size = size,\n            includeAll = includeAll,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname dotplot\n#' @exportMethod dotplot\n#' @aliases dotplot,enrichResultList,ANY-method\n#' @author Guangchuang Yu\nsetMethod(\n    \"dotplot\",\n    signature(object = \"enrichResultList\"),\n    function(\n        object,\n        x = \"GeneRatio\",\n        color = \"p.adjust\",\n        showCategory = 10,\n        size = NULL,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        orderBy = \"x\",\n        label_format = 30,\n        ...\n    ) {\n        dotplot.enrichResult(\n            object = object,\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            orderBy = orderBy,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname dotplot\n#' @exportMethod dotplot\n#' @aliases dotplot,gseaResultList,ANY-method\nsetMethod(\n    \"dotplot\",\n    signature(object = \"gseaResultList\"),\n    function(\n        object,\n        x = \"GeneRatio\",\n        color = \"p.adjust\",\n        showCategory = 10,\n        size = NULL,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        orderBy = \"x\",\n        label_format = 30,\n        ...\n    ) {\n        if (color == \"NES\") {\n            NES <- TRUE\n            color <- \"p.adjust\"\n        } else {\n            NES <- FALSE\n        }\n        p <- dotplot.enrichResult(\n            object = object,\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            orderBy = orderBy,\n            label_format = label_format,\n            ...\n        )\n\n        if (NES) {\n            p <- suppressMessages(\n                p +\n                    aes(fill = .data$NES) +\n                    set_enrichplot_color(type = \"fill\", name = \"NES\")\n            )\n        }\n        return(p)\n    }\n)\n\n#' @rdname dotplot\n#' @param x variable for x-axis, one of 'GeneRatio' and 'Count'\n#' @param color variable used to color enriched terms,\n#'              e.g. 'pvalue', 'p.adjust' or 'qvalue'\n#' @param showCategory number of categories to display or a vector of terms.\n#' @param size variable used to scale the sizes of categories,\n#' one of \"geneRatio\", \"Percentage\" and \"count\"\n#' @param split separate result by 'category' variable\n#' @param font.size font size\n#' @param title plot title\n#' @param label_format a numeric value sets wrap length, alternatively a\n#' custom function to format axis labels.\n#' by default wraps names longer than 30 characters\n#' @param orderBy The order of the Y-axis\n#' @param decreasing logical. Should the orderBy order be increasing or decreasing?\n#' @importFrom ggplot2 fortify\n#' @importFrom ggplot2 ggplot\n#' @importFrom ggplot2 aes\n#' @importFrom ggplot2 geom_point\n#' @importFrom ggplot2 scale_color_gradient\n#' @importFrom ggplot2 scale_color_continuous\n#' @importFrom ggplot2 xlab\n#' @importFrom ggplot2 ylab\n#' @importFrom ggplot2 labs\n#' @importFrom ggplot2 ggtitle\n#' @importFrom ggplot2 scale_y_discrete\n#' @importFrom ggplot2 guides\n#' @importFrom ggplot2 guide_legend\n#' @importFrom methods is\ndotplot.enrichResult <- function(\n    object,\n    x = \"geneRatio\",\n    color = \"p.adjust\",\n    showCategory = 10,\n    size = NULL,\n    split = NULL,\n    font.size = 12,\n    title = \"\",\n    orderBy = \"x\",\n    label_format = 30,\n    decreasing = TRUE\n) {\n    colorBy <- match.arg(color, c(\"pvalue\", \"p.adjust\", \"qvalue\"))\n    .formula_expr <- NULL\n    .orig_x <- x\n    if (x == \"geneRatio\" || x == \"GeneRatio\") {\n        x <- \"GeneRatio\"\n        if (is.null(size)) {\n            size <- \"Count\"\n        }\n    } else if (x == \"count\" || x == \"Count\") {\n        x <- \"Count\"\n        if (is.null(size)) {\n            size <- \"GeneRatio\"\n        }\n    } else if (is(x, \"formula\")) {\n        .formula_expr <- rlang::f_rhs(x)\n        x <- \"x\"\n        if (is.null(size)) {\n            size <- \"Count\"\n        }\n    } else {\n        ## message(\"invalid x, setting to 'GeneRatio' by default\")\n        ## x <- \"GeneRatio\"\n        ## size <- \"Count\"\n        if (is.null(size)) {\n            size <- \"Count\"\n        }\n    }\n\n    if (inherits(object, c(\"enrichResultList\", \"gseaResultList\"))) {\n        ldf <- lapply(\n            object,\n            fortify,\n            showCategory = showCategory,\n            split = split\n        )\n        df <- dplyr::bind_rows(ldf, .id = \"category\")\n        df$category <- factor(df$category, levels = names(object))\n    } else {\n        df <- fortify(object, showCategory = showCategory, split = split)\n        ## already parsed in fortify\n        ## df$GeneRatio <- parse_ratio(df$GeneRatio)\n    }\n\n    if (!is.null(.formula_expr)) {\n        df$x <- rlang::eval_tidy(.formula_expr, data = df)\n    }\n\n    if (orderBy != 'x' && !orderBy %in% colnames(df)) {\n        message('wrong orderBy parameter; set to default `orderBy = \"x\"`')\n        orderBy <- \"x\"\n    }\n\n    if (orderBy == \"x\") {\n        df <- dplyr::mutate(df, x = .data[[x]])\n    }\n\n    label_func <- .label_format(label_format)\n\n    idx <- order(df[[orderBy]], decreasing = decreasing)\n\n    df$Description <- factor(\n        df$Description,\n        levels = rev(unique(df$Description[idx]))\n    )\n\n    # Use internal helper function for common plotting logic\n    p <- .dotplot_internal(\n        df = df,\n        x = x,\n        size = size,\n        colorBy = colorBy,\n        color = color,\n        label_func = label_func,\n        font.size = font.size,\n        title = title\n    )\n    \n    return(p)\n}\n\n.label_format <- function(label_format = 30) {\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n    return(label_func)\n}\n\n#' Internal helper function for dotplot construction\n#' @param df data frame containing the plot data\n#' @param x x-axis variable name\n#' @param size size variable name\n#' @param colorBy color variable name\n#' @param color color parameter name for legend\n#' @param label_func function for formatting labels\n#' @param font.size font size for theme\n#' @param title plot title\n#' @param size_range range for size scaling, default c(3, 8)\n#' @param shape_point whether to use enrichplot_point_shape, default TRUE\n#' @return ggplot object with enrichplotDot class\n#' @noRd\n.dotplot_internal <- function(df, x, size, colorBy, color, label_func, font.size, title, size_range = c(3, 8), shape_point = TRUE) {\n    p <- ggplot(\n        df,\n        aes(\n            x = .data[[x]],\n            y = .data[[\"Description\"]],\n            size = .data[[size]],\n            fill = .data[[colorBy]]\n        )\n    ) +\n        geom_point() +\n        set_enrichplot_color(type = \"fill\", name = color, transform = 'log10') +\n        scale_y_discrete(labels = label_func) +\n        ylab(NULL) +\n        ggtitle(title) +\n        theme_dose(font.size)\n    \n    if (shape_point) {\n        p <- p + aes(shape = I(enrichplot_point_shape))\n    }\n    \n    # Apply size scaling\n    if (size == \"Count\") {\n        # For Count, use pretty breaks\n        size_break <- pretty(df[[size]], n = 4)\n        p <- p + scale_size(range = size_range, breaks = size_break)\n    } else {\n        p <- p + scale_size(range = size_range)\n    }\n    \n    class(p) <- c(\"enrichplotDot\", class(p))\n    return(p)\n}\n\n\n#' @rdname dotplot\n#' @param object compareClusterResult object\n#' @param by one of \"geneRatio\", \"Percentage\" and \"count\"\n#' @param split apply `showCategory` to each category specified by the 'split', e.g., \"ONTOLOGY\", \"category\" and \"intersect\".  Default is NULL and do nothing\n#' @param includeAll logical value\n#' @param font.size font size\n#' @param title figure title\n#' @param group a logical value, whether to connect the\n#' nodes of the same group with wires.\n#' @param shape a logical value, whether to use nodes of\n#' different shapes to distinguish the group it belongs to\n#' @param facet apply `facet_grid` to the plot by specified variable, e.g., \"ONTOLOGY\", \"category\" and \"intersect\".\n#' @param strip_width width of strip text (facet label).\n#' @param colorBy variable used to color enriched terms,\n#' e.g. 'pvalue', 'p.adjust' or 'qvalue'\n#' @importFrom ggplot2 facet_grid\n#' @importFrom ggplot2 scale_size_continuous\n#' @importFrom rlang check_installed\ndotplot.compareClusterResult <- function(\n    object,\n    x = \"Cluster\",\n    colorBy = \"p.adjust\",\n    showCategory = 5,\n    by = \"geneRatio\",\n    size = \"geneRatio\",\n    split = NULL,\n    includeAll = TRUE,\n    font.size = 12,\n    title = \"\",\n    label_format = 30,\n    group = FALSE,\n    shape = FALSE,\n    facet = NULL,\n    strip_width = 15\n) {\n    color <- NULL\n    if (is.null(size)) {\n        size <- by\n    } ## by may deprecated in future release\n\n    if (!is.null(facet) && facet == \"intersect\") {\n        object <- append_intersect(object)\n    }\n\n    df <- fortify(\n        object,\n        showCategory = showCategory,\n        by = size,\n        includeAll = includeAll,\n        split = split\n    )\n\n    # if (by != \"geneRatio\")\n    #    df$GeneRatio <- parse_ratio(df$GeneRatio)\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n\n    if (size %in% c(\"rowPercentage\", \"count\", \"geneRatio\")) {\n        by2 <- switch(\n            size,\n            rowPercentage = \"Percentage\",\n            count = \"Count\",\n            geneRatio = \"GeneRatio\"\n        )\n    } else {\n        by2 <- size\n    }\n\n    # Use internal helper function for base plot, but without shape_point for flexibility\n    p <- .dotplot_internal(\n        df = df,\n        x = x,\n        size = by2,\n        colorBy = colorBy,\n        color = colorBy,\n        label_func = label_func,\n        font.size = font.size,\n        title = title,\n        shape_point = FALSE  # We'll handle shape manually\n    )\n    \n    # Add group connections if requested\n    if (group) {\n        p <- p +\n            geom_line(\n                aes(color = .data$Cluster, group = .data$Cluster),\n                size = .3\n            ) +\n            ggnewscale::new_scale_colour()\n    }\n    \n    # Handle shape variations\n    if (shape) {\n        check_installed('ggstar', 'for `dotplot()` with `shape = TRUE`.')\n        ggstar <- \"ggstar\"\n        require(ggstar, character.only = TRUE)\n        # Replace the base geom_point with ggstar\n        p$layers <- p$layers[-1]  # Remove the first geom_point layer\n        p <- p +\n            ggstar::geom_star(aes(\n                starshape = .data$Cluster,\n                fill = .data[[colorBy]]\n            )) +\n            set_enrichplot_color(type = \"fill\", transform = 'log10')\n    } else {\n        # Add standard point with shape\n        p <- p + aes(shape = I(enrichplot_point_shape))\n    }\n    \n    # Add facet if requested\n    if (!is.null(facet)) {\n        p <- p +\n            facet_grid(\n                .data[[facet]] ~ .,\n                scales = \"free\",\n                space = 'free',\n                switch = 'y',\n                labeller = ggplot2::label_wrap_gen(strip_width)\n            ) +\n            theme(strip.text = element_text(size = 14))\n    }\n    \n    return(p)\n}\n\n\nappend_intersect <- function(x) {\n    if (!inherits(x, 'compareClusterResult')) {\n        stop(\"x should be a compareClusterResult object\")\n    }\n\n    d <- as.data.frame(x)\n\n    so <- vapply(\n        split(d$Cluster, d$Description),\n        FUN = paste,\n        FUN.VALUE = character(1),\n        collapse = \" & \"\n    )\n\n    set_info <- data.frame(\n        intersect = so,\n        Description = names(so)\n    )\n\n    d2 <- merge(d, set_info, by = \"Description\")\n    n <- levels(d2$Cluster)\n    cc <- yulab.utils::combinations(length(n))\n    lv <- vapply(cc, function(i) paste(n[i], collapse = \" & \"), character(1))\n    d2$intersect <- factor(d2$intersect, levels = lv)\n\n    x@compareClusterResult <- d2\n\n    return(x)\n}\n\n#' compare two clusters in the compareClusterResult object\n#'\n#'\n#' @title dotplot2\n#' @param object a compareClusterResult object\n#' @param x selected variable to visualize in x-axis\n#' @param vars selected Clusters to be compared, only length of two is supported\n#' @param label to label the Clusters in the plot, should be a named vector\n#' @param ... additional parameters passed to dotplot\n#' @return a ggplot object\n#' @importFrom ggplot2 geom_segment\n#' @importFrom ggplot2 geom_vline\n#' @importFrom ggplot2 geom_blank\n#' @importFrom grid arrow\n#' @importFrom grid unit\n#' @importFrom ggplot2 geom_text\n#' @export\n#' @author Guangchuang Yu\ndotplot2 <- function(\n    object,\n    x = \"FoldEnrichment\",\n    vars = NULL,\n    label = \"auto\",\n    ...\n) {\n    if (!is(object, 'compareClusterResult')) {\n        stop('only compareClusterResult object is supported')\n    }\n\n    if (length(vars) != 2) {\n        stop(\"vars should be of length 2.\")\n    }\n    object <- dplyr::filter(object, .data$Cluster %in% vars)\n    d <- object@compareClusterResult\n    d[[x]] <- d[[x]] * ifelse(d$Cluster == vars[1], -1, 1)\n    object@compareClusterResult <- d\n    p <- dotplot(object, x = x, ...)\n    p <- p +\n        geom_segment(\n            aes(xend = 0, yend = .data$Description),\n            size = 1,\n            color = 'grey50'\n        ) +\n        geom_vline(xintercept = 0, lty = 'dashed') +\n        scale_x_continuous(labels = abs)\n\n    p$layers <- rev(p$layers)\n\n    if (is.null(label)) {\n        return(p)\n    }\n\n    d <- dplyr::group_by(object, .data$Cluster) |>\n        dplyr::summarise(mid = max(abs(.data[[x]])) * sign(max(.data[[x]])) / 2)\n\n    if (label != \"auto\") {\n        d$Cluster <- label[d$Cluster]\n    }\n\n    p +\n        geom_text(\n            aes(x = .data$mid, y = .4, label = .data$Cluster),\n            data = d,\n            inherit.aes = FALSE,\n            size = 5\n        ) +\n        geom_segment(\n            aes(x = 0, xend = .data$mid, y = .2, yend = .2),\n            data = d,\n            inherit.aes = FALSE,\n            arrow = arrow(length = unit(0.30, \"cm\"), type = \"closed\")\n        ) +\n        geom_blank(\n            data = data.frame(y = 0),\n            aes(y = .data$y),\n            inherit.aes = FALSE\n        )\n}\n"
  },
  {
    "path": "R/emapplot.R",
    "content": "#' @rdname emapplot\n#' @exportMethod emapplot\nsetMethod(\n    \"emapplot\",\n    signature(x = \"enrichResult\"),\n    function(x, showCategory = 30, ...) {\n        emapplot_internal(x, showCategory = showCategory, ...)\n    }\n)\n\n#' @rdname emapplot\n#' @exportMethod emapplot\nsetMethod(\n    \"emapplot\",\n    signature(x = \"gseaResult\"),\n    function(x, showCategory = 30, ...) {\n        emapplot_internal(x, showCategory = showCategory, ...)\n    }\n)\n\n#' @rdname emapplot\n#' @exportMethod emapplot\nsetMethod(\n    \"emapplot\",\n    signature(x = \"compareClusterResult\"),\n    function(x, showCategory = 30, ...) {\n        emapplot_internal(x, showCategory = showCategory, ...)\n    }\n)\n\n\n#' @rdname emapplot\n#' @param layout igraph layout\n#' @param color Variable used to color enriched terms, e.g. 'pvalue',\n#' 'p.adjust' or 'qvalue'.\n#' @param size_category relative size of the categories\n#' @param min_edge The minimum similarity threshold for whether\n#' two nodes are connected, should be between 0 and 1, default value is 0.2.\n#' @param color_edge color of the network edge\n#' @param size_edge relative size of edge width\n#' @param node_label Select which labels to display,\n#' one of 'category', 'group', 'all' and 'none'.\n#' @param node_label_size size of node label, default is 5.\n#' @param pie one of 'equal' or 'Count' to set the slice ratio of the pies\n# @param group logical, if TRUE, group the category.\n# @param group_style style of ellipse, one of \"ggforce\" an \"polygon\".\n# @param label_group_style style of group label, one of \"shadowtext\" and \"ggforce\".\n#' @param label_format a numeric value sets wrap length, alternatively a custom function to format axis labels.\n#' @param clusterFunction clustering method function, such as `stats::kmeans` (default),\n#' `cluster::clara`, `cluster::fanny`, or `cluster::pam`.\n#' @param nWords Numeric, the number of words in the cluster tags, the default value is 4.\n#' @param nCluster Numeric, the number of clusters,\n#' the default value is square root of the number of nodes.\n#' @importFrom ggplot2 scale_size\n#' @importFrom ggtangle geom_edge\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom ggrepel geom_label_repel\n#' @author Guangchuang Yu\nemapplot_internal <- function(\n    x,\n    layout = igraph::layout_with_kk,\n    showCategory = 30,\n    color = \"p.adjust\",\n    size_category = 1,\n    min_edge = .2,\n    color_edge = \"grey\",\n    size_edge = .5,\n    node_label = \"category\",\n    node_label_size = 5,\n    pie = \"equal\",\n    label_format = 30,\n    clusterFunction = stats::kmeans,\n    nWords = 4,\n    nCluster = NULL\n) {\n    if (inherits(x, 'compareClusterResult')) {\n        gg <- graph_from_compareClusterResult(\n            x,\n            showCategory = showCategory,\n            color = color,\n            min_edge = min_edge,\n            size_edge = size_edge\n        )\n    } else {\n        gg <- graph_from_enrichResult(\n            x,\n            showCategory = showCategory,\n            color = color,\n            min_edge = min_edge,\n            size_edge = size_edge\n        )\n    }\n\n    g <- gg$graph\n    size <- vapply(gg$geneSet, length, FUN.VALUE = numeric(1))\n    V(g)$size = size[V(g)$name]\n\n    p <- ggplot(g, layout = layout) +\n        geom_edge(color = color_edge, linewidth = size_edge)\n\n    if (inherits(x, 'compareClusterResult')) {\n        p <- add_node_pie(p, gg$data, pie, category_scale = size_category)\n    } else {\n        if (color %in% names(as.data.frame(x))) {\n            p <- p %<+%\n                x[, c(\"Description\", color)] +\n                geom_point(aes(color = .data[[color]], size = .data$size)) +\n                scale_size(range = c(3, 8) * size_category)\n            p <- p + set_enrichplot_color(colors = get_enrichplot_color(2))\n            p <- p +\n                guides(\n                    size = guide_legend(order = 1),\n                    color = guide_colorbar(order = 2, reverse = TRUE)\n                )\n        } else {\n            p <- p %<+%\n                x[, \"Description\", drop = FALSE] +\n                geom_point(aes(size = .data$size), color = color) +\n                scale_size(range = c(3, 8) * size_category)\n        }\n    }\n\n    group <- group_label <- FALSE\n    if (node_label == \"group\") {\n        group <- TRUE\n    }\n\n    if (node_label == \"all\") {\n        group <- TRUE\n        group_label <- TRUE\n        node_label <- \"category\"\n    }\n\n    if (group) {\n        if (inherits(x, 'compareClusterResult')) {\n            p <- p + ggnewscale::new_scale_fill()\n        } #else {\n        # p <- p + ggnewscale::new_scale_color()\n        #}\n        node_data <- groupNode(\n            p@data,\n            as.data.frame(x),\n            nWords,\n            clusterFunction = clusterFunction,\n            nCluster = nCluster\n        )\n\n        p <- p +\n            add_ellipse(\n                node_data,\n                group_legend = TRUE,\n                label = group_label\n            )\n    }\n\n    ## add node label\n    if (node_label == \"category\") {\n        p <- p +\n            geom_text_repel(\n                aes(label = .data$label),\n                bg.color = \"white\",\n                bg.r = .1,\n                size = node_label_size\n            )\n    }\n    ## add group label\n    if (node_label == \"group\") {\n        label_location <- get_label_location(\n            node_data = node_data,\n            label_format = label_format\n        )\n        p <- p +\n            geom_text_repel(\n                aes(x = .data$x, y = .data$y, label = .data$label),\n                data = label_location,\n                bg.color = \"white\",\n                bg.r = .1,\n                size = node_label_size\n            )\n    }\n\n    p +\n        coord_equal() +\n        guides(\n            size = guide_legend(order = 1),\n            color = guide_colorbar(order = 2)\n        )\n}\n\ngraph_from_enrichResult <- function(\n    x,\n    showCategory = 30,\n    color = \"p.adjust\",\n    min_edge = .2,\n    size_edge = .5\n) {\n    n <- update_n(x, showCategory)\n    y <- as.data.frame(x)\n    ## get graph.data.frame() object\n    g <- get_igraph(\n        x = x,\n        nCategory = n,\n        color = color,\n        cex_line = size_edge,\n        min_edge = min_edge\n    )\n    gs <- extract_geneSets(x, n)\n    return(list(graph = g, geneSet = gs))\n}\n\ngraph_from_compareClusterResult <- function(\n    x,\n    showCategory = 30,\n    color = \"p.adjust\",\n    min_edge = .2,\n    size_edge = .5\n) {\n    d <- tidy_compareCluster(x, showCategory)\n    mergedEnrichDf <- merge_compareClusterResult(d)\n    gs <- setNames(\n        strsplit(as.character(mergedEnrichDf$geneID), \"/\", fixed = TRUE),\n        mergedEnrichDf$ID\n    )\n\n    g <- build_emap_graph(\n        enrichDf = mergedEnrichDf,\n        geneSets = gs,\n        color = color,\n        cex_line = size_edge,\n        min_edge = min_edge,\n        pair_sim = x@termsim,\n        method = x@method\n    )\n    return(list(graph = g, geneSet = gs, data = d))\n}\n"
  },
  {
    "path": "R/emapplot_utilities.R",
    "content": "#' Get the similarity matrix\n#'\n#' @param y A data.frame of enrichment result\n#' @param geneSets A list, the names of geneSets are term ids,\n#' and every element is a vector of genes.\n#' @param method Method of calculating the similarity between nodes,\n#' one of \"Resnik\", \"Lin\", \"Rel\", \"Jiang\" , \"Wang\"  and\n#' \"JC\" (Jaccard similarity coefficient) methods\n#' @param semData GOSemSimDATA object\n#' @noRd\nget_similarity_matrix <- function(y, geneSets, method, semData = NULL) {\n    id <- y[, \"ID\"]\n    geneSets <- geneSets[id]\n    y_id <- unlist(strsplit(y$ID[1], \":\"))[1]\n    ## Choose the method to calculate the similarity\n    if (method == \"JC\") {\n        w <- .cal_jc_similarity(geneSets, id = id, name = y$Description)\n        return(w)\n    }\n\n    if (y_id == \"GO\") {\n        if (is.null(semData)) {\n            stop(\n                \"The semData parameter is missing,\n                and it can be obtained through godata function in GOSemSim package.\"\n            )\n        }\n        w <- GOSemSim::mgoSim(\n            id,\n            id,\n            semData = semData,\n            measure = method,\n            combine = NULL\n        )\n    }\n\n    if (y_id == \"DOID\") {\n        w <- DOSE::doSim(id, id, measure = method)\n    }\n    rownames(y) <- y$ID\n    rownames(w) <- colnames(w) <- y[colnames(w), \"Description\"]\n    return(w)\n}\n\n\n#' Check whether the similarity matrix exists\n#'\n#' @param x result of enrichment analysis\n#'\n#' @noRd\nhas_pairsim <- function(x) {\n    if (length(x@termsim) == 0) {\n        error_message <- paste(\n            \"Term similarity matrix not available.\",\n            \"Please use pairwise_termsim function to\",\n            \"deal with the results of enrichment analysis.\"\n        )\n        stop(error_message)\n    }\n}\n\n\n#' Get graph_from_data_frame() result\n#'\n#' @importFrom igraph graph.empty\n#' @importFrom igraph graph_from_data_frame\n#' @param enrichDf A data.frame of enrichment result.\n#' @param geneSets A list gene sets with the names of enrichment IDs\n#' @param color a string, the column name of y for nodes colours\n#' @param cex_line Numeric, scale of line width\n#' @param min_edge The minimum similarity threshold for whether\n#' two nodes are connected; should be between 0 and 1 (default `0.2`).\n#' @param pair_sim Semantic similarity matrix.\n#' @param method Method of calculating the similarity between nodes,\n#' one of \"Resnik\", \"Lin\", \"Rel\", \"Jiang\" , \"Wang\"  and\n#' \"JC\" (Jaccard similarity coefficient) methods\n#' @return result of graph_from_data_frame()\n#' @importFrom igraph V\n#' @importFrom igraph 'V<-'\n#' @importFrom igraph E\n#' @importFrom igraph 'E<-'\n#' @importFrom igraph add_vertices\n#' @importFrom igraph delete.edges\n#' @noRd\nbuild_emap_graph <- function(\n    enrichDf,\n    geneSets,\n    color,\n    cex_line,\n    min_edge,\n    pair_sim,\n    method\n) {\n    if (!is.numeric(min_edge) || min_edge < 0 || min_edge > 1) {\n        stop('\"min_edge\" should be a number between 0 and 1.')\n    }\n\n    if (is.null(dim(enrichDf)) || nrow(enrichDf) == 1) {\n        # when just one node\n        g <- graph.empty(0, directed = FALSE)\n        g <- add_vertices(g, nv = 1)\n        V(g)$name <- as.character(enrichDf$Description)\n        V(g)$color <- \"red\"\n        return(g)\n    } else {\n        w <- pair_sim[\n            as.character(enrichDf$Description),\n            as.character(enrichDf$Description)\n        ]\n    }\n\n    wd <- reshape2::melt(w)\n    wd <- wd[wd[, 1] != wd[, 2], ]\n    # remove NA\n    wd <- wd[!is.na(wd[, 3]), ]\n    if (method != \"JC\") {\n        # map id to names\n        wd[, 1] <- enrichDf[wd[, 1], \"Description\"]\n        wd[, 2] <- enrichDf[wd[, 2], \"Description\"]\n    }\n\n    g <- graph_from_data_frame(wd[, -3], directed = FALSE)\n    E(g)$width <- sqrt(wd[, 3] * 5) * cex_line\n    # Use similarity as the weight(length) of an edge\n    E(g)$weight <- wd[, 3]\n    g <- delete.edges(g, E(g)[wd[, 3] < min_edge])\n    idx <- unlist(sapply(V(g)$name, function(x) {\n        which(x == enrichDf$Description)\n    }))\n    cnt <- sapply(geneSets[idx], length)\n    V(g)$size <- cnt\n    if (color %in% names(enrichDf)) {\n        colVar <- enrichDf[idx, color]\n    } else {\n        colVar <- color\n    }\n\n    V(g)$color <- colVar\n    return(g)\n}\n\n\n#' Get an iGraph object\n#'\n#' @param x Enrichment result.\n#' @param nCategory Number of enriched terms to display.\n#' @param color variable that used to color enriched terms, e.g. 'pvalue',\n#' 'p.adjust' or 'qvalue'.\n#' @param cex_line Scale of line width.\n#' @param min_edge The minimum similarity threshold for whether\n#' two nodes are connected, should between 0 and 1, default value is 0.2.\n#'\n#' @return an iGraph object\n#' @noRd\nget_igraph <- function(x, nCategory, color, cex_line, min_edge) {\n    y <- as.data.frame(x)\n    geneSets <- geneInCategory(x) ## use core gene for gsea result\n    if (is.numeric(nCategory)) {\n        y <- y[1:nCategory, ]\n    } else {\n        y <- y[match(nCategory, y$Description), ]\n        nCategory <- length(nCategory)\n    }\n\n    if (nCategory == 0) {\n        stop(\"no enriched term found...\")\n    }\n\n    build_emap_graph(\n        enrichDf = y,\n        geneSets = geneSets,\n        color = color,\n        cex_line = cex_line,\n        min_edge = min_edge,\n        pair_sim = x@termsim,\n        method = x@method\n    )\n}\n\n\n#' Merge the compareClusterResult file\n#'\n#' @param yy A data.frame of enrichment result.\n#'\n#' @return a data.frame\n#' @noRd\nmerge_compareClusterResult <- function(yy) {\n    yy_union <- yy[!duplicated(yy$ID), ]\n    yy_ids <- lapply(split(yy, yy$ID), function(x) {\n        ids <- unique(unlist(strsplit(x$geneID, \"/\")))\n        cnt <- length(ids)\n        list(ID = paste0(ids, collapse = \"/\"), cnt = cnt)\n    })\n\n    ids <- vapply(yy_ids, function(x) x$ID, character(1))\n    cnt <- vapply(yy_ids, function(x) x$cnt, numeric(1))\n\n    yy_union$geneID <- ids[yy_union$ID]\n    yy_union$Count <- cnt[yy_union$ID]\n    yy_union$Cluster <- NULL\n    yy_union\n}\n\n\n\n\n\n\n#' Get the location of group label\n#'\n#' @param node_data node information data frame\n#' @param label_format A numeric value sets wrap length, alternatively a\n#' custom function to format axis labels.\n#' @return a data.frame object.\n#' @noRd\nget_label_location <- function(node_data, label_format) {\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n    label_x <- stats::aggregate(x ~ color2, node_data, mean)\n    label_y <- stats::aggregate(y ~ color2, node_data, mean)\n    data.frame(x = label_x$x, y = label_y$y, label = label_func(label_x$color2))\n}\n\n\n#' Cluster similar nodes together by k-means\n#'\n#' @param node_data node information data frame.\n#' @param enrichDf data.frame of enrichment result.\n#' @param nWords Numeric, the number of words in the cluster tags.\n#' @param clusterFunction clustering method function, such as `stats::kmeans`, `cluster::clara`,\n#' `cluster::fanny`, or `cluster::pam`.\n#' @param nCluster Numeric, the number of clusters,\n#' the default value is square root of the number of nodes.\n#' @noRd\ngroupNode <- function(\n    node_data,\n    enrichDf,\n    nWords,\n    clusterFunction = stats::kmeans,\n    nCluster\n) {\n    wrongMessage <- paste(\n        \"Wrong clusterFunction parameter or unsupported clustering method;\",\n        \"set to default `clusterFunction = kmeans`\"\n    )\n    if (is.character(clusterFunction)) {\n        clusterFunction <- eval(parse(text = clusterFunction))\n    }\n    if (!\"color2\" %in% colnames(node_data)) {\n        dat <- data.frame(x = node_data$x, y = node_data$y)\n        nCluster <- ifelse(\n            is.null(nCluster),\n            floor(sqrt(nrow(dat))),\n            min(nCluster, nrow(dat))\n        )\n        node_data$color2 <- tryCatch(\n            expr = clusterFunction(dat, nCluster)$cluster,\n            error = function(e) {\n                message(wrongMessage)\n                clusterFunction(dat, nCluster)$cluster\n            }\n        )\n        if (is.null(node_data$color2)) {\n            message(wrongMessage)\n            node_data$color2 <- clusterFunction(dat, nCluster)$cluster\n        }\n    }\n    goid <- enrichDf$ID\n    cluster_color <- unique(node_data$color2)\n    clusters <- lapply(cluster_color, function(i) {\n        goid[which(node_data$color2 == i)]\n    })\n    cluster_label <- sapply(\n        cluster_color,\n        get_wordcloud,\n        node_data = node_data,\n        nWords = nWords\n    )\n    names(cluster_label) <- cluster_color\n    node_data$color2 <- cluster_label[as.character(node_data$color2)]\n    return(node_data)   \n}\n\n#' Add ellipse to group nodes\n#'\n#' @param node_data node data frame\n#' @param group_legend Logical, if TRUE, the grouping legend will be displayed.\n#' The default is FALSE.\n#' @param label logical, TRUE to label the ellipse (default)\n#' @param ellipse_style style of ellipse, one of \"ggforce\" and \"polygon\".\n#' @param ellipse_pro numeric indicating confidence value for the ellipses\n#' @param alpha the transparency of ellipse fill.\n#' @importFrom rlang check_installed\n#' @importFrom ggplot2 scale_fill_discrete\n#' @noRd\nadd_ellipse <- function(\n    node_data,\n    group_legend,\n    label = TRUE,\n    ellipse_style = \"ggforce\",\n    # ellipse_pro = 0.95,\n    alpha = 0.3,\n    ...\n) {\n    show_legend <- c(group_legend, FALSE)\n    names(show_legend) <- c(\"fill\", \"color\")\n    ellipse_style <- match.arg(ellipse_style, c(\"ggforce\", \"polygon\"))\n\n    check_installed('ggforce', 'for `add_ellipse()`.');\n\n    if (ellipse_style == \"ggforce\") {\n        if (label) {\n            p <- ggforce::geom_mark_ellipse(\n                data = node_data,\n                aes(\n                    x = !!sym('x'),\n                    y = !!sym('y'),\n                    fill = !!sym('color2'),\n                    label = !!sym('color2')\n                ),\n                alpha = alpha,\n                color = NA,\n                show.legend = show_legend\n            )\n        } else {\n            p <- ggforce::geom_mark_ellipse(\n                data = node_data,\n                aes(x = !!sym('x'), y = !!sym('y'), fill = !!sym('color2')),\n                alpha = alpha,\n                color = NA,\n                show.legend = show_legend\n            )\n        }\n    }\n\n    # not in used\n    if (FALSE && ellipse_style == \"polygon\") {\n        ellipse_pro <- 0.95  # Define default ellipse_pro value\n        p <- ggplot2::stat_ellipse(\n            data = node_data,\n            aes(x = !!sym('x'), y = !!sym('y'), fill = !!sym('color2')),\n            geom = \"polygon\",\n            level = ellipse_pro,\n            alpha = alpha,\n            show.legend = group_legend,\n            ...\n        )\n    }\n\n    if (group_legend) {\n        p <- list(p, scale_fill_discrete(name = \"groups\"))\n    }\n\n    return(p)\n}\n\n\nlist2df <- ggtangle:::list2df\n\n"
  },
  {
    "path": "R/enrichplot-package.R",
    "content": "#' @keywords internal\n\"_PACKAGE\"\n\n"
  },
  {
    "path": "R/ggtable.R",
    "content": "#' plot table\n#'\n#'\n#' @title ggtable\n#' @param d data frame\n#' @param p ggplot object to extract color to color rownames(d), optional\n#' @importFrom rlang check_installed\n#' @return ggplot object\n#' @export\n#' @author guangchuang yu\nggtable <- function(d, p = NULL) {\n    # has_package(\"ggplotify\")\n    check_installed('ggplotify', 'for `ggtable()`.')\n    ggplotify::as.ggplot(tableGrob2(d, p))\n}\n\n#' @importFrom grid gpar\n#' @importFrom ggplot2 ggplot_build\n#' @importFrom rlang check_installed\ntableGrob2 <- function(d, p = NULL, rows=NULL) {\n    # has_package(\"gridExtra\")\n    order_index <- order(rownames(d))\n    d <- d[order_index,]\n    if (!is.null(rows)) {\n        rows <- rows[order_index]\n    }\n    check_installed('gridExtra', 'for `tableGrob2()`.')\n    tp <- gridExtra::tableGrob(d, rows=rows)\n    if (is.null(p) || is.null(rows)) {\n        return(tp)\n    }\n\n    # Fix bug: The 'group' order of lines and dots/path is different\n    p_data <- ggplot_build(p)$data[[1]]\n    # pcol <- unique(ggplot_build(p)$data[[1]][[\"colour\"]])\n    p_data <- p_data[order(p_data[[\"group\"]]), ]\n    pcol <- unique(p_data[[\"colour\"]])\n    ## This is fine too\n    ## pcol <- unique(p_data[[\"colour\"]])[unique(p_data[[\"group\"]])]  \n    j <- which(tp$layout$name == \"rowhead-fg\")\n\n    for (i in seq_along(pcol)) {\n        tp$grobs[j][[i+1]][[\"gp\"]] <- gpar(col = pcol[i])\n    }\n    return(tp)\n}\n\n"
  },
  {
    "path": "R/goplot.R",
    "content": "#' @rdname goplot\n#' @exportMethod goplot\nsetMethod(\"goplot\", signature(x = \"enrichResult\"),\n          function(x, showCategory = 10, color = \"p.adjust\",\n                   layout = igraph::layout_with_sugiyama, geom=\"text\", ...) {\n              goplot.enrichResult(x, showCategory = showCategory,\n                  color = color, layout = layout, geom = geom, ...)\n          })\n\n#' @rdname goplot\n#' @exportMethod goplot\nsetMethod(\"goplot\", signature(x = \"gseaResult\"),\n          function(x, showCategory = 10, color = \"p.adjust\",\n                   layout = igraph::layout_with_sugiyama, geom=\"text\", ...) {\n              goplot.enrichResult(x, showCategory = showCategory,\n                  color = color, layout = layout, geom = geom, ...)\n          })\n\n\n\n#' @importFrom utils data\n#' @import GOSemSim\n#' @importFrom ggplot2 scale_fill_gradientn\n#' @importFrom grid arrow\n#' @importFrom grid unit\n#' @importFrom rlang check_installed\n#' @importFrom yulab.utils get_cache_item\ngoplot.enrichResult <- function(x, showCategory = 10, color = \"p.adjust\",\n                                layout = igraph::layout_with_sugiyama, geom = \"text\", \n                                ID = \"Description\", ...) {\n    segment.size <- get_ggrepel_segsize()\n    # has_package(\"AnnotationDbi\")\n    n <- update_n(x, showCategory)\n    geneSets <- geneInCategory(x) ## use core gene for gsea result\n    y <- as.data.frame(x)\n    y <- y[1:n,]\n\n    id <- y$ID[1:n]\n\n    GOSemSim_initial()\n    .GOSemSimEnv <- get_cache_item(\".GOSemSimEnv\")\n    gotbl <- .GOSemSimEnv$gotbl\n\n    if (inherits(gotbl, \"character\")) {\n        utils::data(\"gotbl\", package = \"GOSemSim\", envir = environment())\n        gotbl <- get(\"gotbl\")\n    }\n\n    if (inherits(x, \"gseaResult\")) {\n        onto <- x@setType\n    } else {\n        onto <- x@ontology\n    }\n\n    if (!toupper(onto) %in% c(\"MF\", \"CC\", \"BP\")) {\n        stop(\"Ontology should be one of 'MF', 'CC' or 'BP'\")\n    }\n\n    GOANCESTOR <- getAncestors(onto)\n\n    anc <- GOANCESTOR[id] \n    ca <- anc[[1]]\n    for (i in 2:length(anc)) {\n        ca <- intersect(ca, anc[[i]])\n    }\n\n    uanc <- unique(unlist(anc))\n    uanc <- uanc[!uanc %in% ca]\n    dag <- gotbl[gotbl$go_id %in% unique(c(id, uanc)),]\n\n\n    edge <- dag[, c(5, 1, 4)]\n    node <- unique(gotbl[gotbl$go_id %in% unique(c(edge[,1], edge[,2])), 1:3])\n    node$color <- x[node$go_id, color]\n    node$size <- sapply(geneSets[node$go_id], length)\n\n    g <- graph_from_data_frame(edge, directed=TRUE, vertices=node)\n    E(g)$relationship <- edge[,3]\n\n    check_installed('ggarchery', 'for `goplot()`.')\n\n    position = ggarchery::position_attractsegment(\n            start_shave=.03, \n            end_shave=.03,\n            type_shave=\"proportion\"\n        )\n    p <- ggplot(g, layout = layout) +\n        geom_edge(aes(linetype = .data$relationship),\n            arrow = arrow(length = unit(2, 'mm')),\n            colour=\"darkgrey\", position=position, linewidth = 1) \n\n    if (ID == \"Description\" || ID == \"ID\") {\n        ID <- sprintf(\"{%s}\", ID)\n    } \n\n    if (geom == \"label\") {\n        p <- p + geom_label_repel(aes(label= glue::glue(ID, ID=.data[['name']], Description=.data[['Term']]), \n                        fill=.data$color, segment.size = segment.size)) +\n            set_enrichplot_color(type = \"fill\", name = color, na.value=\"white\")\n    } else {\n        p <- p + geom_point(aes(color=.data$color), size=5) +\n            geom_text_repel(aes(label=glue::glue(ID, ID=.data[['name']], Description=.data[['Term']])), \n                    segment.size = segment.size, bg.color=\"white\", bg.r=.1) +\n            set_enrichplot_color(type = \"color\", name = color, na.value=\"grey\")\n    }        \n        \n    return(p)\n}\n\n#' @importFrom utils getFromNamespace\nGOSemSim_initial <- getFromNamespace(\".initial\", \"GOSemSim\")\ngetAncestors <- getFromNamespace(\"getAncestors\", \"GOSemSim\")\n"
  },
  {
    "path": "R/gseaplot.R",
    "content": "#' @rdname gseaplot\n#' @exportMethod gseaplot\nsetMethod(\n    \"gseaplot\",\n    signature(x = \"gseaResult\"),\n    function(\n        x,\n        geneSetID,\n        by = \"all\",\n        title = \"\",\n        color = 'black',\n        color.line = \"green\",\n        color.vline = \"#FA5860\",\n        ...\n    ) {\n        gseaplot.gseaResult(\n            x,\n            geneSetID = geneSetID,\n            by = by,\n            title = title,\n            color = color,\n            color.line = color.line,\n            color.vline = color.vline,\n            ...\n        )\n    }\n)\n\n#' @rdname gseaplot\n#' @param color color of line segments\n#' @param color.line color of running enrichment score line\n#' @param color.vline color of vertical line indicating the\n#' maximum/minimal running enrichment score\n#' @return ggplot2 object\n#' @importFrom ggplot2 ggplot\n#' @importFrom ggplot2 geom_linerange\n#' @importFrom ggplot2 geom_line\n#' @importFrom ggplot2 geom_vline\n#' @importFrom ggplot2 geom_hline\n#' @importFrom ggplot2 xlab\n#' @importFrom ggplot2 ylab\n#' @importFrom ggplot2 xlim\n#' @importFrom ggplot2 aes\n#' @importFrom ggplot2 ggplotGrob\n#' @importFrom ggplot2 geom_segment\n#' @importFrom ggplot2 ggplot_gtable\n#' @importFrom ggplot2 ggplot_build\n#' @importFrom ggplot2 ggtitle\n#' @importFrom ggplot2 element_text\n#' @importFrom ggplot2 rel\n#' @importFrom aplot plot_list\n#' @author Guangchuang Yu\ngseaplot.gseaResult <- function(\n    x,\n    geneSetID,\n    by = \"all\",\n    title = \"\",\n    color = 'black',\n    color.line = \"green\",\n    color.vline = \"#FA5860\",\n    ...\n) {\n    by <- match.arg(by, c(\"runningScore\", \"preranked\", \"all\"))\n    gsdata <- gsInfo(x, geneSetID)\n    p <- ggplot(gsdata, aes(x = .data$x)) +\n        theme_dose() +\n        xlab(\"Position in the Ranked List of Genes\")\n    if (by == \"runningScore\" || by == \"all\") {\n        p.res <- p +\n            geom_linerange(\n                aes(ymin = .data$ymin, ymax = .data$ymax),\n                color = color\n            )\n        p.res <- p.res +\n            geom_line(\n                aes(y = .data$runningScore),\n                color = color.line,\n                linewidth = 1\n            )\n        enrichmentScore <- x@result[geneSetID, \"enrichmentScore\"]\n        es.df <- data.frame(\n            es = which.min(abs(p$data$runningScore - enrichmentScore))\n        )\n        p.res <- p.res +\n            geom_vline(\n                data = es.df,\n                aes(xintercept = .data$es),\n                colour = color.vline,\n                linetype = \"dashed\"\n            )\n        p.res <- p.res + ylab(\"Running Enrichment Score\")\n        p.res <- p.res + geom_hline(yintercept = 0)\n    }\n    if (by == \"preranked\" || by == \"all\") {\n        df2 <- data.frame(x = which(p$data$position == 1))\n        df2$y <- p$data$geneList[df2$x]\n        p.pos <- p +\n            geom_segment(\n                data = df2,\n                aes(x = .data$x, xend = .data$x, y = .data$y, yend = 0),\n                color = color\n            )\n        p.pos <- p.pos +\n            ylab(\"Ranked List Metric\") +\n            xlim(0, length(p$data$geneList))\n    }\n    if (by == \"runningScore\") {\n        return(p.res + ggtitle(title))\n    }\n    if (by == \"preranked\") {\n        return(p.pos + ggtitle(title))\n    }\n\n    p.pos <- p.pos +\n        xlab(NULL) +\n        theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())\n    p.pos <- p.pos +\n        ggtitle(title) +\n        theme(plot.title = element_text(hjust = 0.5, size = rel(2)))\n    #plot_list(gglist =  list(p.pos, p.res), ncol=1)\n\n    aplot::gglist(gglist = list(p.pos, p.res), ncol = 1)\n}\n\n\n#' extract gsea result of selected geneSet\n#'\n#'\n#' @title gsInfo\n#' @param object gseaResult object\n#' @param geneSetID gene set ID\n#' @return data.frame\n#' @author Guangchuang Yu\n## @export\ngsInfo <- function(object, geneSetID) {\n    geneList <- object@geneList\n\n    if (is.numeric(geneSetID)) {\n        geneSetID <- object@result[geneSetID, \"ID\"]\n    }\n\n    geneSet <- object@geneSets[[geneSetID]]\n    exponent <- object@params[[\"exponent\"]]\n    df <- gseaScores(geneList, geneSet, exponent, fortify = TRUE)\n    df$ymin <- 0\n    df$ymax <- 0\n    pos <- df$position == 1\n    h <- diff(range(df$runningScore)) / 20\n    df$ymin[pos] <- -h\n    df$ymax[pos] <- h\n    df$geneList <- geneList\n    if (length(object@gene2Symbol) == 0) {\n        df$gene <- names(geneList)\n    } else {\n        df$gene <- object@gene2Symbol[names(geneList)]\n    }\n\n    df$Description <- object@result[geneSetID, \"Description\"]\n    return(df)\n}\n\n\nget_gsdata <- function(x, geneSetID) {\n    if (length(geneSetID) == 1) {\n        gsdata <- gsInfo(x, geneSetID)\n        return(gsdata)\n    }\n\n    lapply(geneSetID, gsInfo, object = x) |>\n        yulab.utils::rbindlist()\n}\n\n#' Horizontal plot for GSEA result\n#'\n#'\n#' @title hplot\n#' @param x gseaResult object\n#' @param geneSetID gene set ID\n#' @return horizontal plot\n#' @export\n#' @author Guangchuang Yu\nhplot <- function(x, geneSetID) {\n    if (!inherits(x, \"gseaResult\")) {\n        stop(\"hplot only work for GSEA result\")\n    }\n\n    gsdata <- get_gsdata(x, geneSetID)\n\n    ggplot(gsdata, aes(.data$x, .data$runningScore)) +\n        ggHoriPlot::geom_horizon(origin = 'min', horizonscale = 4) +\n        facet_grid(Description ~ .) +\n        #ggHoriPlot::scale_fill_hcl(palette = 'Peach', reverse = TRUE) +\n        ggHoriPlot::scale_fill_hcl(palette = 'BluGrn', reverse = TRUE) +\n        theme_minimal() +\n        ggfun::theme_noyaxis() +\n        theme(\n            panel.spacing.y = unit(0, \"lines\"),\n            strip.text.y = element_text(angle = 0),\n            legend.position = 'none',\n            panel.border = element_blank(),\n            panel.grid = element_blank(),\n        ) +\n        xlab(NULL) +\n        ylab(NULL)\n}\n\n#' GSEA plot that mimic the plot generated by broad institute's GSEA software\n#'\n#'\n#' @title gseaplot2\n#' @param x gseaResult object\n#' @param geneSetID gene set ID\n#' @param title plot title\n#' @param color color of running enrichment score line\n#' @param base_size base font size\n#' @param rel_heights relative heights of subplots\n#' @param subplots which subplots to be displayed\n#' @param pvalue_table whether add pvalue table\n#' @param pvalue_table_columns selected columns to be plotted in the `pvalue_table`\n#' @param pvalue_table_rownames selected column as the rownames of the `pvalue_table`. If set to NULL, no rownames will be displayed.\n#' @param ES_geom geom for plotting running enrichment score,\n#' one of 'line' or 'dot'\n#' @return plot\n#' @export\n#' @importFrom ggplot2 theme_classic\n#' @importFrom ggplot2 element_line\n#' @importFrom ggplot2 element_text\n#' @importFrom ggplot2 element_blank\n#' @importFrom ggplot2 element_rect\n#' @importFrom ggplot2 scale_x_continuous\n#' @importFrom ggplot2 scale_y_continuous\n#' @importFrom ggplot2 scale_color_manual\n#' @importFrom ggplot2 theme_void\n#' @importFrom ggplot2 geom_rect\n#' @importFrom ggplot2 margin\n#' @importFrom ggplot2 annotation_custom\n#' @importFrom stats quantile\n#' @importFrom RColorBrewer brewer.pal\n#' @author Guangchuang Yu\ngseaplot2 <- function(\n    x,\n    geneSetID,\n    title = \"\",\n    color = \"green\",\n    base_size = 11,\n    rel_heights = c(1.5, .5, 1),\n    subplots = 1:3,\n    pvalue_table = FALSE,\n    pvalue_table_columns = c(\"pvalue\", \"p.adjust\"),\n    pvalue_table_rownames = \"Description\",\n    ES_geom = \"line\"\n) {\n    ES_geom <- match.arg(ES_geom, c(\"line\", \"dot\"))\n\n    geneList <- position <- NULL ## to satisfy codetool\n\n    gsdata <- get_gsdata(x, geneSetID)\n\n    p <- ggplot(gsdata, aes(x = .data$x)) +\n        xlab(NULL) +\n        theme_classic(base_size) +\n        theme(\n            panel.grid.major = element_line(colour = \"grey92\"),\n            panel.grid.minor = element_line(colour = \"grey92\"),\n            panel.grid.major.y = element_blank(),\n            panel.grid.minor.y = element_blank()\n        ) +\n        scale_x_continuous(expand = c(0, 0))\n\n    if (ES_geom == \"line\") {\n        es_layer <- geom_line(\n            aes(y = .data$runningScore, color = .data$Description),\n            linewidth = 1\n        )\n    } else {\n        es_layer <- geom_point(\n            aes(y = .data$runningScore, color = .data$Description),\n            size = 1,\n            data = subset(gsdata, position == 1)\n        )\n    }\n\n    p.res <- p +\n        es_layer +\n        theme(\n            legend.position = \"inside\",\n            legend.position.inside = c(.8, .8),\n            legend.title = element_blank(),\n            legend.background = element_rect(fill = \"transparent\")\n        )\n\n    p.res <- p.res +\n        ylab(\"Running Enrichment Score\") +\n        theme(\n            axis.text.x = element_blank(),\n            axis.ticks.x = element_blank(),\n            axis.line.x = element_blank(),\n            plot.margin = margin(t = .2, r = .2, b = 0, l = .2, unit = \"cm\")\n        )\n\n    # Vectorized ymin/ymax assignment\n    terms <- unique(gsdata$Description)\n    term_indices <- match(gsdata$Description, terms) - 1\n    idx <- which(gsdata$ymin != 0)\n    gsdata[idx, \"ymin\"] <- term_indices[idx]\n    gsdata[idx, \"ymax\"] <- term_indices[idx] + 1\n    p2 <- ggplot(gsdata, aes(x = .data$x)) +\n        geom_linerange(aes(\n            ymin = .data$ymin,\n            ymax = .data$ymax,\n            color = .data$Description\n        )) +\n        xlab(NULL) +\n        ylab(NULL) +\n        theme_classic(base_size) +\n        theme(\n            legend.position = \"none\",\n            plot.margin = margin(t = -.1, b = 0, unit = \"cm\"),\n            axis.ticks = element_blank(),\n            axis.text = element_blank(),\n            axis.line.x = element_blank()\n        ) +\n        scale_x_continuous(expand = c(0, 0)) +\n        scale_y_continuous(expand = c(0, 0))\n\n    if (length(geneSetID) == 1) {\n        ## geneList <- gsdata$geneList\n        ## j <- which.min(abs(geneList))\n        ## v1 <- quantile(geneList[1:j], seq(0,1, length.out=6))[1:5]\n        ## v2 <- quantile(geneList[j:length(geneList)], seq(0,1, length.out=6))[1:5]\n\n        ## v <- sort(c(v1, v2))\n        ## inv <- findInterval(geneList, v)\n\n        v <- seq(1, sum(gsdata$position), length.out = 9)\n        inv <- findInterval(rev(cumsum(gsdata$position)), v)\n        if (min(inv) == 0) {\n            inv <- inv + 1\n        }\n\n        col <- c(rev(brewer.pal(5, \"Blues\")), brewer.pal(5, \"Reds\"))\n\n        ymin <- min(p2$data$ymin)\n        yy <- max(p2$data$ymax - p2$data$ymin) * .3\n        xmin <- which(!duplicated(inv))\n        xmax <- xmin + as.numeric(table(inv)[as.character(unique(inv))])\n        d <- data.frame(\n            ymin = ymin,\n            ymax = yy,\n            xmin = xmin,\n            xmax = xmax,\n            col = col[unique(inv)]\n        )\n        p2 <- p2 +\n            geom_rect(\n                aes(\n                    xmin = .data$xmin,\n                    xmax = .data$xmax,\n                    ymin = .data$ymin,\n                    ymax = .data$ymax,\n                    fill = I(col)\n                ),\n                data = d,\n                alpha = .9,\n                inherit.aes = FALSE\n            )\n    }\n\n    ## p2 <- p2 +\n    ## geom_rect(aes(xmin=x-.5, xmax=x+.5, fill=geneList),\n    ##           ymin=ymin, ymax = ymin + yy, alpha=.5) +\n    ## theme(legend.position=\"none\") +\n    ## scale_fill_gradientn(colors=color_palette(c(\"blue\", \"red\")))\n\n    df2 <- p$data #data.frame(x = which(p$data$position == 1))\n    df2$y <- p$data$geneList[df2$x]\n    p.pos <- p +\n        geom_segment(\n            data = df2,\n            aes(x = .data$x, xend = .data$x, y = .data$y, yend = 0),\n            color = \"grey\"\n        )\n    p.pos <- p.pos +\n        ylab(\"Ranked List Metric\") +\n        xlab(\"Rank in Ordered Dataset\") +\n        theme(\n            plot.margin = margin(t = -.1, r = .2, b = .2, l = .2, unit = \"cm\")\n        )\n\n    if (!is.null(title) && !is.na(title) && title != \"\") {\n        p.res <- p.res + ggtitle(title)\n    }\n\n    if (length(color) == length(geneSetID)) {\n        p.res <- p.res + scale_color_manual(values = color)\n        if (length(color) == 1) {\n            p.res <- p.res + theme(legend.position = \"none\")\n            p2 <- p2 + scale_color_manual(values = \"black\")\n        } else {\n            p2 <- p2 + scale_color_manual(values = color)\n        }\n    }\n\n    if (pvalue_table) {\n        pd <- x[geneSetID, pvalue_table_columns]\n        # pd <- pd[order(pd[,1], decreasing=FALSE),]\n        if (is.null(pvalue_table_rownames)) {\n            rows <- NULL\n        } else {\n            # rownames(pd) <- pd$Description\n            if (length(pvalue_table_rownames) != 1) {\n                stop(\n                    \"the length of `pvalue_table_rownames` should be equal to 1\"\n                )\n            }\n\n            rows <- x[geneSetID, pvalue_table_rownames]\n        }\n\n        # pd <- round(pd, 4)\n        for (i in seq_len(ncol(pd))) {\n            pd[, i] <- format(pd[, i], digits = 4)\n        }\n        tp <- tableGrob2(d = pd, p = p.res, rows = rows)\n\n        p.res <- p.res +\n            theme(legend.position = \"none\") +\n            annotation_custom(\n                tp,\n                xmin = quantile(p.res$data$x, .5),\n                xmax = quantile(p.res$data$x, .95),\n                ymin = quantile(p.res$data$runningScore, .75),\n                ymax = quantile(p.res$data$runningScore, .9)\n            )\n    }\n\n    plotlist <- list(p.res, p2, p.pos)[subplots]\n    n <- length(plotlist)\n    plotlist[[n]] <- plotlist[[n]] +\n        theme(\n            axis.line.x = element_line(),\n            axis.ticks.x = element_line(),\n            axis.text.x = element_text()\n        )\n\n    if (length(subplots) == 1) {\n        return(\n            plotlist[[1]] +\n                theme(\n                    plot.margin = margin(\n                        t = .2,\n                        r = .2,\n                        b = .2,\n                        l = .2,\n                        unit = \"cm\"\n                    )\n                )\n        )\n    }\n\n    if (length(rel_heights) > length(subplots)) {\n        rel_heights <- rel_heights[subplots]\n    }\n\n    # aplot::plot_list(gglist = plotlist, ncol=1, heights=rel_heights)\n    aplot::gglist(gglist = plotlist, ncol = 1, heights = rel_heights)\n}\n\n\n#' plot ranked list of genes with running enrichment score as bar height\n#'\n#'\n#' @title gsearank\n#' @param x gseaResult object\n#' @param geneSetID gene set ID\n#' @param title plot title\n#' @param output one of 'plot' or 'table' (for exporting data)\n#' @return ggplot object\n#' @importFrom ggplot2 geom_segment\n#' @importFrom ggplot2 theme_minimal\n#' @export\n#' @author Guangchuang Yu\ngsearank <- function(x, geneSetID, title = \"\", output = \"plot\") {\n    output <- match.arg(output, c(\"plot\", \"table\"))\n\n    position <- NULL\n    gsdata <- gsInfo(x, geneSetID)\n    gsdata <- subset(gsdata, position == 1)\n\n    if (output == \"table\") {\n        res <- gsdata[, c(\"gene\", \"x\", \"runningScore\")]\n        if (x[geneSetID, \"NES\"] > 0) {\n            res$core <- \"NO\"\n            res$core[1:which.max(gsdata$runningScore)] <- \"YES\"\n        } else {\n            res$core <- \"NO\"\n            res$core[which.min(gsdata$runningScore):nrow(res)] <- \"YES\"\n        }\n        names(res) <- c(\n            \"gene\",\n            \"rank in geneList\",\n            \"running ES\",\n            \"core enrichment\"\n        )\n        rownames(res) <- NULL\n        return(res)\n    }\n\n    p <- ggplot(gsdata, aes(x = .data$x, y = .data$runningScore)) +\n        geom_segment(aes(xend = .data$x, yend = 0)) +\n        ggtitle(title) +\n        xlab(\"Position in the Ranked List of Genes\") +\n        ylab(\"Running Enrichment Score\") +\n        theme_minimal()\n    return(p)\n}\n\n\n#' label genes in running score plot\n#'\n#'\n#' @title geom_gsea_gene\n#' @param genes selected genes to be labeled\n#' @param mapping aesthetic mapping, default is NULL\n#' @param geom geometric layer to plot the gene labels, default is geom_text\n#' @param ... additional parameters passed to the 'geom'\n#' @param geneSet choose which gene set(s) to be label if the plot contains multiple gene sets\n#' @return ggplot object\n#' @importFrom rlang .data\n#' @export\n#' @author Guangchuang Yu\ngeom_gsea_gene <- function(\n    genes,\n    mapping = NULL,\n    geom = ggplot2::geom_text,\n    ...,\n    geneSet = NULL\n) {\n    default_mapping <- aes(\n        x = .data$x,\n        y = .data$runningScore,\n        label = .data$gene\n    )\n    if (is.null(mapping)) {\n        mapping <- default_mapping\n    } else {\n        mapping <- modifyList(default_mapping, mapping)\n    }\n    if (is.null(geneSet)) {\n        data <- ggtree::td_filter(.data$gene %in% genes)\n    } else {\n        data <- ggtree::td_filter(\n            .data$gene %in% genes & .data$Description %in% geneSet\n        )\n    }\n\n    geom(mapping = mapping, data = data, ...)\n}\n"
  },
  {
    "path": "R/heatplot.R",
    "content": "#' @rdname heatplot\n#' @exportMethod heatplot\nsetMethod(\n    \"heatplot\",\n    signature(x = \"enrichResult\"),\n    function(x, showCategory = 30, ...) {\n        heatplot.enrichResult(x, showCategory, ...)\n    }\n)\n\n#' @rdname heatplot\n#' @exportMethod heatplot\nsetMethod(\n    \"heatplot\",\n    signature(x = \"gseaResult\"),\n    function(x, showCategory = 30, ...) {\n        heatplot.enrichResult(x, showCategory, ...)\n    }\n)\n\n\n#' @rdname heatplot\n#' @importFrom ggplot2 geom_tile\n#' @importFrom ggplot2 theme_minimal\n#' @importFrom ggplot2 theme\n#' @importFrom ggplot2 element_blank\n#' @importFrom ggplot2 element_text\n#' @importFrom ggplot2 scale_y_discrete\n#' @importFrom ggplot2 scale_fill_gradient2\n#' @importFrom rlang check_installed\n#' @param showTop number of top genes ranked by `abs(foldChange) * frequency`\n#' to be shown in the heatmap, default NULL means all genes are shown\n#' @param label_format a numeric value sets wrap length, alternatively a\n#' custom function to format axis labels.\n#' by default wraps names longer than 30 characters\n#' @param symbol symbol of the nodes, one of \"rect\" (the default) or \"dot\"\n#' @param pvalue pvalue of genes\n#' @author Guangchuang Yu\nheatplot.enrichResult <- function(\n    x,\n    showCategory = 30,\n    showTop = NULL,\n    symbol = \"rect\",\n    foldChange = NULL,\n    pvalue = NULL,\n    label_format = 30\n) {\n    symbol <- match.arg(symbol, c(\"rect\", \"dot\"))\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n\n    n <- update_n(x, showCategory)\n    geneSets <- extract_geneSets(x, n)\n    if (!is.null(showTop) && showTop > 0) {\n        nfreq <- table(unlist(geneSets))\n        nfc <- nfreq * abs(foldChange[names(nfreq)])\n        topgenes <- head(names(sort(nfc, decreasing = TRUE)), showTop)\n        geneSets <- lapply(geneSets, function(s) intersect(s, topgenes))\n    }\n    foldChange <- fc_readable(x, foldChange)\n    pvalue <- fc_readable(x, pvalue)\n    d <- list2df(geneSets)\n    if (!is.null(foldChange)) {\n        d$foldChange <- foldChange[as.character(d[, 2])]\n    }\n\n    if (!is.null(pvalue)) {\n        d$pvalue <- pvalue[as.character(d[, 2])]\n    }\n\n    p <- ggplot(d, aes(x = .data$Gene, y = .data$categoryID))\n\n    if (symbol == \"rect\") {\n        p <- p + geom_tile(color = 'white')\n    }\n\n    get_dotp <- function(p, foldChange, pvalue) {\n        if (is.null(foldChange) && is.null(pvalue)) {\n            p <- p +\n                geom_point(\n                    color = 'black',\n                    shape = 21,\n                    fill = \"black\",\n                    size = 5\n                )\n            return(p)\n        }\n        if (!is.null(foldChange) && !is.null(pvalue)) {\n            p <- p + geom_point(color = 'black', shape = 21)\n            return(p)\n        }\n\n        if (is.null(foldChange)) {\n            p <- p + geom_point(color = 'black', shape = 21, fill = \"black\")\n        } else {\n            p <- p + geom_point(color = 'black', shape = 21, size = 5)\n        }\n\n        return(p)\n    }\n\n    # copy from https://stackoverflow.com/questions/11053899/how-to-get-a-reversed-log10-scale-in-ggplot2\n    reverselog_trans <- function(base = exp(1)) {\n        trans <- function(x) -log(x, base)\n\n        check_installed('scales', 'for `heatplot()`.')\n\n        inv <- function(x) base^(-x)\n        scales::trans_new(\n            paste0(\"reverselog-\", format(base)),\n            trans,\n            inv,\n            scales::log_breaks(base = base),\n            domain = c(1e-100, Inf)\n        )\n    }\n\n    if (symbol == \"dot\") {\n        p <- get_dotp(p, foldChange, pvalue)\n        ## only dot need size(pvalue) parameter\n        if (!is.null(pvalue)) {\n            p <- p +\n                aes(size = .data$pvalue) +\n                scale_size_continuous(\n                    range = c(3, 8),\n                    trans = reverselog_trans(10)\n                )\n        }\n    }\n\n    if (!is.null(foldChange)) {\n        p <- p +\n            aes(fill = !!sym('foldChange')) +\n            set_enrichplot_color(\n                colors = get_enrichplot_color(3),\n                type = \"fill\",\n                reverse = FALSE,\n                transform = 'identity'\n            )\n    }\n\n    p +\n        xlab(NULL) +\n        ylab(NULL) +\n        theme_minimal() +\n        scale_y_discrete(labels = label_func) +\n        theme(\n            panel.grid.major = element_blank(),\n            axis.text.x = element_text(angle = 60, hjust = 1)\n        )\n}\n"
  },
  {
    "path": "R/manhattanplot.R",
    "content": "#' @rdname manhattanplot\n#' @exportMethod manhattanplot\n#' @author Guangchuang Yu\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"enrichResult\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        size = \"Count\",\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        label_format = 30,\n        ...\n    ) {\n        manhattanplot.enrichResult(\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname manhattanplot\n#' @exportMethod manhattanplot\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"gseaResult\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        size = \"Count\",\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        label_format = 30,\n        ...\n    ) {\n        manhattanplot.enrichResult(\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname manhattanplot\n#' @aliases manhattanplot,compareClusterResult,ANY-method\n#' @exportMethod manhattanplot\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"compareClusterResult\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        size = \"Count\",\n        includeAll = TRUE,\n        label_format = 30,\n        ...\n    ) {\n        manhattanplot.compareClusterResult(\n            x,\n            colorBy = color,\n            showCategory = showCategory,\n            size = size,\n            includeAll = includeAll,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname manhattanplot\n#' @exportMethod manhattanplot\n#' @aliases manhattanplot,enrichResultList,ANY-method\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"enrichResultList\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        size = \"Count\",\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        label_format = 30,\n        ...\n    ) {\n        manhattanplot.enrichResult(\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname manhattanplot\n#' @exportMethod manhattanplot\n#' @aliases manhattanplot,gseaResultList,ANY-method\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"gseaResultList\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        size = \"Count\",\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        label_format = 30,\n        ...\n    ) {\n        manhattanplot.enrichResult(\n            x = x,\n            color = color,\n            showCategory = showCategory,\n            size = size,\n            split = split,\n            font.size = font.size,\n            title = title,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n#' @rdname manhattanplot\n#' @exportMethod manhattanplot\n#' @aliases manhattanplot,list,ANY-method\nsetMethod(\n    \"manhattanplot\",\n    signature(x = \"list\"),\n    function(\n        x,\n        color = \"p.adjust\",\n        showCategory = 5,\n        size = \"Count\",\n        split = NULL,\n        font.size = 12,\n        title = \"\",\n        label_format = 30,\n        ...\n    ) {\n        if (all(sapply(x, function(i) inherits(i, \"enrichResult\") || inherits(i, \"gseaResult\")))) {\n            class(x) <- \"enrichResultList\"\n            manhattanplot(\n                x = x,\n                color = color,\n                showCategory = showCategory,\n                size = size,\n                split = split,\n                font.size = font.size,\n                title = title,\n                label_format = label_format,\n                ...\n            )\n        } else {\n            stop(\"all elements in the list should be enrichResult or gseaResult objects\")\n        }\n    }\n)\n\n#' Internal helper function for manhattan build\n#' @noRd\n\n.get_ontology <- function(x) {\n    if (\"ontology\" %in% methods::slotNames(x) && length(x@ontology) > 0 && x@ontology != \"\") {\n        return(x@ontology)\n    }\n    if (\"fun\" %in% methods::slotNames(x) && length(x@fun) > 0 && x@fun != \"\") {\n        if (x@fun == \"enrichGO\" || x@fun == \"gseGO\") {\n           return(\"GO\")\n        }\n        res <- gsub(\"enrich\", \"\", x@fun) \n        res <- gsub(\"gse\", \"\", res)\n        return(res)\n    }\n    return(\"Enrichment\")\n}\n\n.prep_manhattan_df <- function(df, colorBy) {\n    if (nrow(df) == 0) return(list(df = df))\n    \n    grp_col <- \"ONTOLOGY\"\n    if (!\"ONTOLOGY\" %in% colnames(df)) {\n        if (\"Category\" %in% colnames(df)) {\n            grp_col <- \"Category\"\n        } else {\n            df$ONTOLOGY <- \"Enrichment\"\n        }\n    }\n    \n    unique_terms <- unique(df[, c(\"ID\", grp_col)])\n    unique_terms <- unique_terms[order(unique_terms[[grp_col]], unique_terms$ID), ]\n    \n    unique_terms$x_pos <- NA\n    grps <- unique(unique_terms[[grp_col]])\n    \n    current_x <- 0\n    ticks <- numeric(length(grps))\n    gap <- max(1, nrow(unique_terms) * 0.05)\n    \n    for (i in seq_along(grps)) {\n        grp <- grps[i]\n        idx <- which(unique_terms[[grp_col]] == grp)\n        n <- length(idx)\n        unique_terms$x_pos[idx] <- current_x + (1:n)\n        ticks[i] <- current_x + n / 2\n        current_x <- current_x + n + gap\n    }\n    \n    df <- merge(df, unique_terms, by = c(\"ID\", grp_col))\n    \n    # Calculate y\n    df$y <- -log10(df[[colorBy]])\n    \n    list(df = df, ticks = ticks, grps = grps, grp_col = grp_col)\n}\n\n.manhattanplot_internal <- function(df, ticks, grps, grp_col, hl_df, size, colorBy, label_func, font.size, title, size_range = c(3, 8)) {\n    p <- ggplot(df, aes(x = .data$x_pos, y = .data$y)) +\n        geom_point(aes(size = .data[[size]], fill = .data[[grp_col]]), shape = 21, alpha = 0.8) +\n        scale_x_continuous(breaks = ticks, labels = grps) +\n        ylab(paste0(\"-log10(\", colorBy, \")\")) +\n        xlab(NULL) +\n        ggtitle(title) +\n        theme_dose(font.size) +\n        theme(\n            panel.grid.minor = element_blank(),\n            panel.grid.major.x = element_blank(),\n            axis.text.x = element_text(angle = 45, hjust = 1)\n        )\n    \n    if (size == \"Count\" && !is.null(df[[size]])) {\n        tryCatch({\n            size_break <- pretty(df[[size]], n = 4)\n            p <- p + scale_size(range = size_range, breaks = size_break)\n        }, error = function(e) {\n            p <- p + scale_size(range = size_range)\n        })\n    } else {\n        p <- p + scale_size(range = size_range)\n    }\n    \n    if (nrow(hl_df) > 0) {\n        rlang::check_installed('ggrepel', 'for labeling in `manhattanplot()`.')\n        hl_df$label <- label_func(hl_df$Description)\n        p <- p + ggrepel::geom_text_repel(\n            data = hl_df,\n            aes(x = .data$x_pos, y = .data$y, label = .data$label),\n            size = font.size / 3,\n            min.segment.length = 0,\n            box.padding = 0.5,\n            show.legend = FALSE\n        )\n    }\n    \n    class(p) <- c(\"enrichplotManhattan\", class(p))\n    return(p)\n}\n\n#' @importFrom ggplot2 ggplot aes geom_point scale_x_continuous xlab ylab ggtitle theme element_text element_blank scale_size theme_void\n#' @importFrom utils head\nmanhattanplot.enrichResult <- function(\n    x,\n    color = \"p.adjust\",\n    showCategory = 5,\n    size = \"Count\",\n    split = NULL,\n    font.size = 12,\n    title = \"\",\n    label_format = 30,\n    ...\n) {\n    colorBy <- match.arg(color, c(\"pvalue\", \"p.adjust\", \"qvalue\"))\n\n    if (inherits(x, c(\"enrichResultList\", \"gseaResultList\"))) {\n        ldf <- lapply(x, as.data.frame)\n        n_all <- sum(sapply(ldf, nrow))\n        if (n_all == 0) return(ggplot() + theme_void())\n        \n        ldf <- lapply(seq_along(x), function(i) {\n            obj <- x[[i]]\n            df_i <- fortify(obj, showCategory = nrow(as.data.frame(obj)))\n            if (!\"ONTOLOGY\" %in% colnames(df_i)) {\n               df_i$ONTOLOGY <- .get_ontology(obj)\n            }\n            return(df_i)\n        })\n        names(ldf) <- names(x)\n        df <- dplyr::bind_rows(ldf, .id = \"category\")\n        df$category <- factor(df$category, levels = names(x))\n    } else {\n        n_all <- nrow(as.data.frame(x))\n        if (n_all == 0) return(ggplot() + theme_void())\n        df <- fortify(x, showCategory = n_all, split = split)\n        if (!\"ONTOLOGY\" %in% colnames(df)) {\n           df$ONTOLOGY <- .get_ontology(x)\n        }\n    }\n\n    res <- .prep_manhattan_df(df, colorBy)\n    df <- res$df\n    \n    if (!is.null(showCategory) && showCategory > 0) {\n        df_ord <- df[order(df$y, decreasing = TRUE), ]\n        hl_df <- head(df_ord, showCategory)\n    } else {\n        hl_df <- df[0, ]\n    }\n\n    label_func <- .label_format(label_format)\n\n    p <- .manhattanplot_internal(\n        df = df,\n        ticks = res$ticks,\n        grps = res$grps,\n        grp_col = res$grp_col,\n        hl_df = hl_df,\n        size = size,\n        colorBy = colorBy,\n        label_func = label_func,\n        font.size = font.size,\n        title = title\n    )\n    \n    return(p)\n}\n\n#' @importFrom ggplot2 facet_grid\nmanhattanplot.compareClusterResult <- function(\n    x,\n    colorBy = \"p.adjust\",\n    showCategory = 5,\n    size = \"Count\",\n    split = NULL,\n    includeAll = TRUE,\n    font.size = 12,\n    title = \"\",\n    label_format = 30,\n    facet = \"Cluster\",\n    strip_width = 15,\n    ...\n) {\n    if (!is.null(facet) && facet == \"intersect\") {\n        x <- append_intersect(x)\n    }\n\n    n_all <- nrow(as.data.frame(x))\n    if (n_all == 0) return(ggplot() + theme_void())\n    \n    df <- fortify(x, showCategory = n_all, includeAll = includeAll, split = split)\n    if (!\"ONTOLOGY\" %in% colnames(df)) {\n       df$ONTOLOGY <- .get_ontology(x)\n    }\n\n    # In single enrich we didn't use `colorBy`, we used `color`. For compare we mapped it to colorBy.\n    colorBy <- match.arg(colorBy, c(\"pvalue\", \"p.adjust\", \"qvalue\"))\n\n    res <- .prep_manhattan_df(df, colorBy)\n    df <- res$df\n\n    if (!is.null(showCategory) && showCategory > 0) {\n        df_ord <- df[order(df$y, decreasing = TRUE), ]\n        hl_df <- do.call(rbind, by(df_ord, df_ord[[facet]], head, n = showCategory))\n    } else {\n        hl_df <- df[0, ]\n    }\n\n    label_func <- .label_format(label_format)\n\n    p <- .manhattanplot_internal(\n        df = df,\n        ticks = res$ticks,\n        grps = res$grps,\n        grp_col = res$grp_col,\n        hl_df = hl_df,\n        size = size,\n        colorBy = colorBy,\n        label_func = label_func,\n        font.size = font.size,\n        title = title\n    )\n    \n    if (!is.null(facet)) {\n        p <- p +\n            facet_grid(\n                stats::reformulate(\".\", response = facet),\n                scales = \"free_y\",\n                space = 'fixed',\n                switch = 'y',\n                labeller = ggplot2::label_wrap_gen(strip_width)\n            ) +\n            theme(strip.text = element_text(size = 14))\n    }\n    \n    return(p)\n}\n"
  },
  {
    "path": "R/method-fortify.R",
    "content": "#' convert compareClusterResult to a data.frame that ready for plot\n#'\n#'\n#' @rdname fortify\n#' @title fortify\n#' @param includeAll logical\n#' @return data.frame\n#' @importFrom ggplot2 fortify\n#' @importFrom dplyr arrange\n#' @importFrom dplyr desc\n#' @importFrom dplyr group_by\n#' @importFrom dplyr slice_head\n#' @importFrom dplyr ungroup\n#' @importFrom dplyr bind_rows\n#' @importFrom dplyr mutate\n#' @importFrom dplyr %>%\n#' @export\n#' @author Guangchuang Yu\nfortify.compareClusterResult <- function(\n    model,\n    data,\n    showCategory = 5,\n    by = \"geneRatio\",\n    split = NULL,\n    includeAll = TRUE,\n    ...\n) {\n    clProf.df <- as.data.frame(model)\n    .split <- split\n    if (\"core_enrichment\" %in% colnames(clProf.df)) {\n        clProf.df$Count <- str_count(clProf.df$core_enrichment, \"/\")\n        clProf.df$.sign <- \"activated\"\n        clProf.df$.sign[clProf.df$NES < 0] <- \"suppressed\"\n        clProf.df$GeneRatio <- clProf.df$Count / clProf.df$setSize\n    }\n    ## get top 5 (default) categories of each gene cluster.\n    if (is.null(showCategory)) {\n        result <- clProf.df\n    } else if (is.numeric(showCategory)) {\n        topN <- function(res, showCategory) {\n            if (\"pvalue\" %in% colnames(res)) {\n                res <- arrange(res, .data$pvalue)\n            } else {\n                ## for groupGO\n                res <- arrange(res, desc(.data$Count))\n            }\n\n            res %>% \n                group_by(.data$Cluster) %>% \n                slice_head(n = showCategory) %>% \n                ungroup() %>%\n                as.data.frame()\n        }\n\n        if (!is.null(.split) && .split %in% colnames(clProf.df)) {\n            lres <- split(clProf.df, as.character(clProf.df[, .split]))\n            lres <- lapply(lres, topN, showCategory = showCategory)\n            result <- as.data.frame(bind_rows(lres))\n        } else {\n            result <- topN(clProf.df, showCategory)\n        }\n    } else {\n        result <- subset(clProf.df, Description %in% showCategory)\n    }\n\n    ID <- NULL\n    if (includeAll == TRUE) {\n        result <- subset(clProf.df, ID %in% result$ID)\n    }\n\n    ## remove zero count\n    result$Description <- as.character(result$Description) ## un-factor\n    GOlevel <- result[, c(\"ID\", \"Description\")] ## GO ID and Term\n    GOlevel <- unique(GOlevel)\n\n    result <- result[result$Count != 0, ]\n    result$Description <- factor(\n        result$Description,\n        levels = unique(rev(GOlevel[, 2]))\n    )\n    if (by == \"rowPercentage\") {\n        Description <- Count <- NULL # to satisfy codetools\n        result <- result %>%\n            group_by(.data$Description) %>%\n            mutate(\n                Percentage = .data$Count / sum(.data$Count),\n                Total = sum(.data$Count)\n            ) %>%\n            ungroup() %>%\n            as.data.frame()\n\n        ## label GO Description with gene counts.\n        result$Description <- paste0(result$Description, \" (\", result$Total, \")\")\n\n        ## restore the original order of GO Description\n        xx <- result[, c(2, 3)]\n        xx <- unique(xx)\n        rownames(xx) <- xx[, 1]\n        Termlevel <- xx[as.character(GOlevel[, 1]), 2]\n\n        ##drop the *Total* column\n        result <- result[, colnames(result) != \"Total\"]\n\n        result$Description <- factor(\n            result$Description,\n            levels = unique(rev(Termlevel))\n        )\n    } else if (by == \"count\") {\n        result$GeneRatio <- yulab.utils::parse_ratio(result$GeneRatio)\n    } else if (by == \"geneRatio\") {\n        ## for result of ORA\n        # if (class(result$GeneRatio) == \"character\" && grep(\"/\", result$GeneRatio[1])) {\n        if (\n            inherits(result$GeneRatio, \"character\") &&\n                grep(\"/\", result$GeneRatio[1])\n        ) {\n            gcsize <- as.numeric(sub(\n                \"^\\\\d+/\",\n                \"\",\n                as.character(result$GeneRatio)\n            ))\n            result$GeneRatio <- yulab.utils::parse_ratio(result$GeneRatio)\n            if (\n                (\"ONTOLOGY\" %in% colnames(result)) &&\n                    (length(unique(result$ONTOLOGY)) > 1)\n            ) {\n                # do nothing\n            } else {\n                cluster <- paste(\n                    as.character(result$Cluster),\n                    \"\\n\",\n                    \"(\",\n                    gcsize,\n                    \")\",\n                    sep = \"\"\n                )\n                orig_cls <- unique(result$Cluster)\n                num_cls <- suppressWarnings(as.numeric(as.character(orig_cls)))\n                \n                if (any(is.na(num_cls))) {\n                    idx <- order(orig_cls)\n                } else {\n                    idx <- order(num_cls)\n                }\n                \n                lv <- unique(cluster)[idx]\n                result$Cluster <- factor(cluster, levels = lv)\n            }\n        }\n    } else {\n        ## nothing\n    }\n    return(result)\n}\n\n\n#' convert enrichResult object for ggplot2\n#'\n#'\n#' @title fortify\n#' @rdname fortify\n#' @param model 'enrichResult' or 'compareClusterResult' object\n#' @param data not use here\n#' @param showCategory Category numbers to show\n#' @param by one of Count and GeneRatio\n#' @param order logical\n#' @param drop logical\n#' @param split separate result by 'split' variable\n#' @param ... additional parameter\n#' @return data.frame\n#' @importFrom ggplot2 fortify\n## @method fortify enrichResult\n#' @export\nfortify.enrichResult <- function(\n    model,\n    data,\n    showCategory = 5,\n    by = \"Count\",\n    order = FALSE,\n    drop = FALSE,\n    split = NULL,\n    ...\n) {\n    fortify_internal(\n        model = model,\n        data = data,\n        showCategory = showCategory,\n        by = by,\n        order = order,\n        drop = drop,\n        split = split\n    )\n}\n\n## @method fortify gseaResult\n#' @export\nfortify.gseaResult <- function(\n    model,\n    data,\n    showCategory = 5,\n    by = \"Count\",\n    order = FALSE,\n    drop = FALSE,\n    split = NULL,\n    ...\n) {\n    fortify_internal(model, data, showCategory, by, order, drop, split)\n}\n\n\nfortify_internal <- function(\n    model,\n    data,\n    showCategory = 5,\n    by = \"Count\",\n    order = FALSE,\n    drop = FALSE,\n    split = NULL\n) {\n    res <- as.data.frame(model)\n    res <- res[!is.na(res$Description), ]\n    if (inherits(model, \"gseaResult\")) {\n        res$Count <- str_count(res$core_enrichment, \"/\")\n        res$.sign <- \"activated\"\n        res$.sign[res$NES < 0] <- \"suppressed\"\n    }\n    if (drop) {\n        res <- res[res$Count != 0, ]\n    }\n    if (inherits(model, \"gseaResult\")) {\n        res$GeneRatio <- res$Count / res$setSize\n    } else if (inherits(model, \"enrichResult\")) {\n        res$GeneRatio <- parse_ratio(res$GeneRatio)\n        if (\"BgRatio\" %in% colnames(res)) {\n            ## groupGO output doesn't have this column\n            res$BgRatio <- parse_ratio(res$BgRatio)\n        }\n    }\n\n    if (order) {\n        if (by == \"Count\") {\n            idx <- order(res$Count, decreasing = TRUE)\n        } else {\n            idx <- order(res$GeneRatio, decreasing = TRUE)\n        }\n        res <- res[idx, ]\n    }\n\n    topN <- function(res, showCategory) {\n        if (is.numeric(showCategory)) {\n            if (showCategory <= nrow(res)) {\n                res <- res[1:showCategory, ]\n            }\n        } else {\n            ## selected categories\n            res <- res[res$Description %in% showCategory, ]\n        }\n        return(res)\n    }\n\n    if (is.null(split)) {\n        res <- topN(res, showCategory)\n    } else {\n        lres <- split(res, as.character(res[, split]))\n        lres <- lapply(lres, topN, showCategory = showCategory)\n        res <- do.call('rbind', lres)\n    }\n\n    res$Description <- factor(\n        res$Description,\n        levels = rev(unique(res$Description))\n    )\n\n    return(res)\n}\n\nstr_count <- function(string, pattern = \"\") {\n    sapply(string, FUN = function(i) {\n        length(unlist(strsplit(i, split = pattern)))\n    })\n}\n\nparse_ratio <- function(ratio) {\n    gsize <- as.numeric(sub(\"/\\\\d+$\", \"\", as.character(ratio)))\n    gcsize <- as.numeric(sub(\"^\\\\d+/\", \"\", as.character(ratio)))\n    return(gsize / gcsize)\n}\n"
  },
  {
    "path": "R/method-ggplot-add.R",
    "content": "#' @importFrom ggplot2 ggplot_add\n#' @method ggplot_add autofacet\n#' @export\nggplot_add.autofacet <- function(object, plot, ...) {\n    d <- plot$data\n    nn <- names(d)\n    if ('category' %in% nn) {\n        var <- \"category\"\n    } else if ('ONTOLOGY' %in% nn) {\n        var <- 'ONTOLOGY'\n    } else {\n        message(\"not supported\")\n        return(plot)\n    }\n\n    if (!is.null(object$levels)) {\n        d[[var]] <- factor(d[[var]], levels = object$levels)\n        plot$data <- d\n    }\n    if (object$by == 'row') {\n        obj <- facet_grid(.data[[var]] ~ ., scales=object$scales)\n    } else {\n        obj <- facet_grid(. ~ .data[[var]], scales=object$scales)\n    }\n    ggplot_add(obj, plot, ...)\n}\n"
  },
  {
    "path": "R/method-print.r",
    "content": "#' @method print enrichplotDot\n#' @export\nprint.enrichplotDot <- function(x, ...) {\n    p <- ggfun::set_point_legend_shape(x)\n    class(p) <- class(p)[-1]\n    print(p)\n}\n"
  },
  {
    "path": "R/pairwise_termsim.R",
    "content": "#' @rdname pairwise_termsim\n#' @exportMethod pairwise_termsim\nsetMethod(\"pairwise_termsim\", signature(x = \"enrichResult\"),\n    function(x, method = \"JC\", semData = NULL, showCategory = NULL) {\n        pairwise_termsim.enrichResult(x, method = method,\n            semData = semData, showCategory = showCategory)\n    })\n\n#' @rdname pairwise_termsim\n#' @exportMethod pairwise_termsim\nsetMethod(\"pairwise_termsim\", signature(x = \"gseaResult\"),\n    function(x, method = \"JC\", semData = NULL, showCategory = NULL) {\n        pairwise_termsim.enrichResult(x, method = method,\n            semData = semData, showCategory = showCategory)\n    })\n\n#' @rdname pairwise_termsim\n#' @exportMethod pairwise_termsim\nsetMethod(\"pairwise_termsim\", signature(x = \"compareClusterResult\"),\n    function(x, method = \"JC\", semData = NULL, showCategory = NULL) {\n        pairwise_termsim.compareClusterResult(x, method = method,\n            semData = semData, showCategory = showCategory)\n    })\n\n\n#' @rdname pairwise_termsim\npairwise_termsim.enrichResult <- function(x, method = \"JC\", semData = NULL, showCategory = NULL) {\n    if (is.null(showCategory)) {\n        showCategory <- .default_pairwise_termsim_category(x)\n    }\n\n    y <- as.data.frame(x)\n    geneSets <- geneInCategory(x)\n    n <- update_n(x, showCategory)\n    if (n == 0) stop(\"no enriched term found...\")\n    if (is.numeric(n)) {\n        y <- y[1:n, ]\n    } else {\n        y <- y[match(n, y$Description),]\n        n <- length(n)\n    }\n\n    x@termsim <- get_similarity_matrix(y = y, geneSets = geneSets, method = method,\n                semData = semData)\n    x@method <- method\n    return(x)\n}\n\n\n#' @rdname pairwise_termsim\npairwise_termsim.compareClusterResult <- function(x, method = \"JC\", semData = NULL, \n                                                  showCategory = NULL) {\n    if (is.null(showCategory)) {\n        showCategory <- .default_pairwise_termsim_category(x)\n    }\n\n    y <- fortify(x, showCategory=showCategory, includeAll=TRUE, split=NULL)\n    y$Cluster <- sub(\"\\n.*\", \"\", y$Cluster)\n    ## y_union <- get_y_union(y = y, showCategory = showCategory)\n    if (\"core_enrichment\" %in% colnames(y)) {\n        y$geneID <- y$core_enrichment\n    }\n    y_union <- merge_compareClusterResult(y)\n    geneSets <- setNames(strsplit(as.character(y_union$geneID), \"/\",\n                                  fixed = TRUE), \n                         y_union$ID)\n    x@termsim <- get_similarity_matrix(y = y_union, geneSets = geneSets, method = method,\n                semData = semData)                              \n    x@method <- method\n    return(x)    \n}\n\n\n.default_pairwise_termsim_category <- function(x, min_default = 200) {\n    min(nrow(x), min_default)\n}\n"
  },
  {
    "path": "R/plot_utils.R",
    "content": "#' Plotting utility functions for enrichplot package\n#'\n#' This file contains plotting and visualization helper functions for enrichplot\n\n#' Automatically split barplot or dotplot into several facets\n#'\n#' @param by one of 'row' or 'column'\n#' @param scales whether 'fixed' or 'free'\n#' @param levels set facet levels\n#' @return a ggplot object\n#' @export\nautofacet <- function(by = 'row', scales = \"free\", levels = NULL) {\n    structure(\n        list(by = by, scales = scales, levels = levels),\n        class = \"autofacet\"\n    )\n}\n\n#' Internal plot function for plotting compareClusterResult\n#'\n#' @param clProf.reshape.df data frame of compareCluster result\n#' @param x x variable\n#' @param type one of dot and bar\n#' @param by one of percentage and count\n#' @param title graph title\n#' @param font.size graph font size\n#' @param colorBy one of pvalue or p.adjust\n#' @return ggplot object\n#' @importFrom ggplot2 ggplot\n#' @importFrom ggplot2 aes\n#' @importFrom ggplot2 geom_bar\n#' @importFrom ggplot2 coord_flip\n#' @importFrom ggplot2 geom_point\n#' @importFrom ggplot2 %+%\n#' @importFrom ggplot2 theme\n#' @importFrom ggplot2 xlab\n#' @importFrom ggplot2 ylab\n#' @importFrom ggplot2 theme_bw\n#' @importFrom ggplot2 element_text\n#' @importFrom ggplot2 ggtitle\n#' @importFrom ggplot2 scale_color_continuous\n#' @importFrom ggplot2 guide_colorbar\n#' @author Guangchuang Yu <https://yulab-smu.top>\nplotting.clusterProfile <- function(\n    clProf.reshape.df,\n    x = ~Cluster,\n    type = \"dot\",\n    colorBy = \"p.adjust\",\n    by = \"geneRatio\",\n    title = \"\",\n    font.size = 12\n) {\n    if (type == \"bar\") {\n        if (by == \"percentage\") {\n            p <- ggplot(\n                clProf.reshape.df,\n                aes(\n                    x = !!sym(\"Description\"),\n                    y = !!sym(\"Percentage\"),\n                    fill = !!sym(\"Cluster\")\n                )\n            )\n        } else if (by == \"count\") {\n            p <- ggplot(\n                clProf.reshape.df,\n                aes(\n                    x = !!sym(\"Description\"),\n                    y = !!sym(\"Count\"),\n                    fill = !!sym(\"Cluster\")\n                )\n            )\n        } else {}\n        p <- p +\n            geom_bar() +\n            coord_flip()\n    }\n\n    p <- p + xlab(\"\") + ylab(\"\") + ggtitle(title) + theme_dose(font.size)\n    return(p)\n}\n\n#' Get the distance of the label\n#'\n#' @param dimension one of 1 and 2\n#' @param label_location label_location\n#' @return distance matrix\n#' @noRd\nget_label_diss <- function(dimension, label_location) {\n    nn <- nrow(label_location)\n    label_dis <- matrix(NA, nrow = nn, ncol = nn)\n    colnames(label_dis) <- rownames(label_dis) <- label_location$label\n\n    # Vectorized computation using outer\n    vals <- label_location[[dimension]]\n    label_dis <- outer(vals, vals, `-`)\n    colnames(label_dis) <- rownames(label_dis) <- label_location$label\n\n    # Convert to long format\n    label_diss <- reshape2::melt(label_dis)\n    label_diss <- label_diss[label_diss[, 1] != label_diss[, 2], ]\n    label_diss <- label_diss[!is.na(label_diss[, 3]), ]\n    label_diss[, 1] <- as.character(label_diss[, 1])\n    label_diss[, 2] <- as.character(label_diss[, 2])\n    return(label_diss)\n}\n\n#' Default labeller function\n#'\n#' Default labeling function that uses the\n#' internal string wrapping function `yulab.utils::str_wrap`\n#' @noRd\n#' @importFrom yulab.utils str_wrap\ndefault_labeller <- function(n) {\n    fun <- function(str) {\n        str <- gsub(\"_\", \" \", str)\n        yulab.utils::str_wrap(str, n)\n    }\n\n    structure(fun, class = \"labeller\")\n}\n\n#' Get segment.size value for ggrepel\n#'\n#' @param default default value of ggrepel.segment.size\n#' @return segment size value\n#' @noRd\nget_ggrepel_segsize <- function(default = 0.2) {\n    getOption(\"ggrepel.segment.size\", default = default)\n}\n\n\n#' Get parameter change message\n#'\n#' @param parameter parameter name\n#' @param params_df parameter data frame\n#' @return warning message\n#' @noRd\nget_param_change_message <- function(parameter, params_df) {\n    paste0(\n        \"Use '\",\n        params_df[parameter, \"listname\"],\n        \" = list(\",\n        params_df[parameter, \"present\"],\n        \" = your_value)' instead of '\",\n        params_df[parameter, \"original\"],\n        \"'\"\n    )\n}\n"
  },
  {
    "path": "R/pmcplot.R",
    "content": "#' PubMed Central Trend plot\n#'\n#'\n#' @title pmcplot\n#' @param query query terms\n#' @param period period of query in the unit of year\n#' @param proportion If TRUE, use query_hits/all_hits, otherwise use query_hits.\n#' @return ggplot object\n#' @importFrom purrr map_df\n#' @importFrom rlang check_installed\n## @importFrom europepmc epmc_hits_trend\n#' @importFrom utils modifyList\n#' @export\n#' @author Guangchuang Yu\npmcplot <- function(query, period, proportion = TRUE) {\n    \n    check_installed('europepmc', 'for `pmcplot()`.')\n    \n    res <- map_df(query, function(x) {\n        period <- get(\"period\", parent.env(parent.env(new.env())))\t\n\ty <- europepmc::epmc_hits_trend(query = x, period = period)\n        y$query <- x\n        return(y)\n    })\n\n    mapping <- aes(x = .data$year, y = .data$query_hits, color = .data$query)\n    ylab <- \"Number of articles\"\n    if (proportion) {\n    mapping <- modifyList(mapping, aes(y = .data$query_hits/.data$all_hits))\n        ylab <- \"Proportion of articles\"\n    }\n    ggplot(res, mapping) + geom_line() + geom_point() +\n        xlab(NULL) + ylab(ylab)\n}\n\n\n"
  },
  {
    "path": "R/reexport.R",
    "content": "#' @importFrom ggplot2 ggtitle\n#' @export\nggplot2::ggtitle\n\n#' @importFrom ggplot2 facet_grid\n#' @export\nggplot2::facet_grid\n\n#' @importFrom aplot plot_list\n#' @export\naplot::plot_list\n\n#' @importFrom ggtangle cnetplot\n#' @export\nggtangle::cnetplot\n\n#' @importFrom DOSE theme_dose\n#' @export \nDOSE::theme_dose\n\n#' @importFrom ggtangle geom_cnet_label\n#' @export \nggtangle::geom_cnet_label\n\n#' @importFrom enrichit gseaScores\n#' @export\nenrichit::gseaScores\n\n#' @importFrom enrichit geneID\n#' @export\nenrichit::geneID\n\n#' @importFrom enrichit geneInCategory\n#' @export\nenrichit::geneInCategory\n\n#' @importClassesFrom enrichit compareClusterResult\nNULL\n"
  },
  {
    "path": "R/ridgeplot.R",
    "content": "#' @rdname ridgeplot\n#' @exportMethod ridgeplot\nsetMethod(\n    \"ridgeplot\",\n    signature(x = \"gseaResult\"),\n    function(\n        x,\n        showCategory = 30,\n        fill = \"p.adjust\",\n        core_enrichment = TRUE,\n        label_format = 30,\n        ...\n    ) {\n        ridgeplot.gseaResult(\n            x,\n            showCategory = showCategory,\n            fill = fill,\n            core_enrichment = core_enrichment,\n            label_format = label_format,\n            ...\n        )\n    }\n)\n\n\n#' @rdname ridgeplot\n#' @param orderBy The order of the Y-axis\n#' @param decreasing logical. Should the orderBy order be increasing or decreasing?\n#' @param stat statistic passed to `ggridges::geom_density_ridges()`.\n#' @importFrom ggplot2 scale_fill_gradientn\n#' @importFrom ggplot2 scale_x_reverse\n#' @importFrom ggplot2 xlab\n#' @importFrom ggplot2 ylab\n#' @importFrom ggplot2 scale_y_discrete\n#' @importFrom rlang check_installed\n#' @importFrom yulab.utils yulab_abort\n#' @importFrom yulab.utils yulab_warn\n#' @author Guangchuang Yu\nridgeplot.gseaResult <- function(\n    x,\n    showCategory = 30,\n    fill = \"p.adjust\",\n    core_enrichment = TRUE,\n    label_format = 30,\n    orderBy = \"NES\",\n    decreasing = FALSE,\n    stat = \"density_ridges\"\n) {\n    ## Input validation with better error messages\n    check_input(x, type = \"gseaResult\", arg_name = \"x\")\n    \n    if (!fill %in% colnames(x@result)) {\n        yulab_abort(paste0(\"'\", fill, \"' variable not available in result\"), \n                        class = \"missing_column_error\")\n    }\n\n    ## geom_density_ridges <- get_fun_from_pkg('ggridges', 'geom_density_ridges')\n    if (orderBy != 'NES' && !orderBy %in% colnames(x@result)) {\n        yulab_warn('wrong orderBy parameter; set to default `orderBy = \"NES\"`',\n                     class = \"parameter_warning\")\n        orderBy <- \"NES\"\n    }\n    \n    ## Optimized category selection\n    if (inherits(showCategory, 'numeric')) {\n        selected <- seq_len(min(showCategory, nrow(x@result)))\n    } else if (inherits(showCategory, \"character\")) {\n        ii <- match(showCategory, x@result$Description)\n        if (all(is.na(ii))) {\n            ii <- match(showCategory, x@result$ID)\n        }\n        ii <- ii[!is.na(ii)]\n        if (length(ii) == 0) {\n            yulab_warn(\"No matching categories found, using first 10\",\n                          class = \"category_warning\")\n            ii <- seq_len(min(10, nrow(x@result)))\n        }\n        selected <- x@result[ii, \"ID\"]\n    } else {\n        yulab_warn(\"showCategory should be a number of pathways or a vector of selected pathways\",\n                       class = \"parameter_warning\")\n        selected <- seq_len(min(10, nrow(x@result)))\n    }\n\n    ## Optimized gene set extraction\n    if (core_enrichment) {\n        gs2id <- geneInCategory(x)[selected]\n    } else {\n        gs2id <- x@geneSets[names(x@geneSets) %in% selected]\n    }\n\n    ## Optimized gene name mapping\n    if (x@readable && length(x@gene2Symbol) > 0) {\n        gene_names <- names(x@geneList)\n        symbol_match <- match(gene_names, names(x@gene2Symbol))\n        valid_matches <- !is.na(symbol_match)\n        names(x@geneList)[valid_matches] <- x@gene2Symbol[symbol_match[valid_matches]]\n    }\n\n    ## Vectorized data preparation\n    gs2val <- lapply(gs2id, function(id) {\n        res <- x@geneList[id]\n        res[!is.na(res)]\n    })\n\n    nn <- names(gs2val)\n    i <- match(nn, x$ID)\n    nn <- x$Description[i]\n\n    ## Optimized ordering\n    order_values <- x@result[[orderBy]][i]\n    j <- order(order_values, decreasing = decreasing)\n    \n    ## Efficient data frame construction\n    len <- lengths(gs2val)\n    total_len <- sum(len)\n    \n    gs2val.df <- data.frame(\n        category = rep(nn, times = len),\n        color = rep(x[i, fill], times = len),\n        value = unlist(gs2val, use.names = FALSE)\n    )\n\n    colnames(gs2val.df)[2] <- fill\n    gs2val.df$category <- factor(gs2val.df$category, levels = nn[j])\n\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n\n    check_installed('ggridges', 'for `ridgeplot()`.')\n\n    ggplot(\n        gs2val.df,\n        aes(x = .data[[\"value\"]], y = .data[[\"category\"]], fill = .data[[fill]])\n    ) +\n        ggridges::geom_density_ridges(stat = stat) +\n        set_enrichplot_color(type = \"fill\", name = fill, transform = 'log10') +\n        scale_y_discrete(labels = label_func) +\n        xlab(NULL) +\n        ylab(NULL) +\n        theme_dose()\n}\n"
  },
  {
    "path": "R/ssplot.R",
    "content": "#' @rdname ssplot\n#' @exportMethod ssplot\nsetMethod(\n    \"ssplot\",\n    signature(x = \"enrichResult\"),\n    function(x, showCategory = 30, ...) {\n        ssplot.enrichResult(x, showCategory = showCategory, ...)\n    }\n)\n\n#' @rdname ssplot\n#' @exportMethod ssplot\nsetMethod(\n    \"ssplot\",\n    signature(x = \"gseaResult\"),\n    function(x, showCategory = 30, ...) {\n        ssplot.enrichResult(x, showCategory = showCategory, ...)\n    }\n)\n\n#' @rdname ssplot\n#' @exportMethod ssplot\nsetMethod(\n    \"ssplot\",\n    signature(x = \"compareClusterResult\"),\n    function(x, showCategory = 30, ...) {\n        ssplot.compareClusterResult(x, showCategory = showCategory, ...)\n    }\n)\n\n\n#' @rdname ssplot\n#' @param drfun The function used for dimension reduction,\n#' e.g. `stats::cmdscale` (the default), `vegan::metaMDS`, or `ape::pcoa`.\n#' @param dr.params list, the parameters of `tidydr::dr`.\n#' @inheritParams emapplot\n#' @param ... additional parameters\n#'\n#' Additional plotting parameters are inherited from [emapplot()].\n#' @importFrom tidydr theme_dr\nssplot.enrichResult <- function(\n    x,\n    showCategory = 30,\n    drfun = NULL,\n    dr.params = list(),\n    #group = TRUE,\n    node_label = \"group\",\n    ...\n) {\n    if (is.null(drfun)) {\n        drfun = stats::cmdscale\n        dr.params = list(eig = TRUE)\n    }\n    if (is.character(drfun)) {\n        drfun <- eval(parse(text = drfun))\n    }\n\n    drResult <- get_drResult(\n        x = x,\n        showCategory = showCategory,\n        drfun = drfun,\n        dr.params = dr.params\n    )\n    coords <- drResult$drdata[, c(1, 2)]\n    colnames(coords) <- c(\"x\", \"y\")\n    rownames(coords) <- attr(drResult$data, \"Labels\")\n    p <- emapplot(\n        x = x,\n        showCategory = showCategory,\n        #group = group,\n        node_label = node_label,\n        ...\n    )\n\n    ## Set axis label according to drfun\n    p <- adj_axis(p = p, drResult = drResult)\n\n    p + theme_dr()\n}\n\n\n#' @rdname ssplot\n#' @importFrom ggplot2 theme_classic\n#' @importFrom ggplot2 coord_equal\n# @param cex_pie2axis Adjust the relative size of the pie chart on the axes (default `0.0125`).\n#' @importFrom stats setNames\nssplot.compareClusterResult <- function(\n    x,\n    showCategory = 30,\n    #split = NULL,\n    pie = \"equal\",\n    drfun = NULL,\n    #cex_pie2axis = 0.0125,\n    dr.params = list(),\n    node_label = \"group\",\n    ...\n) {\n    if (is.null(drfun)) {\n        drfun = stats::cmdscale\n        dr.params = list(eig = TRUE)\n    }\n\n    if (is.character(drfun)) {\n        drfun <- eval(parse(text = drfun))\n    }\n    split = NULL\n    drResult <- get_drResult(\n        x = x,\n        showCategory = showCategory,\n        split = split,\n        pie = pie,\n        drfun = drfun,\n        dr.params = dr.params\n    )\n    coords <- drResult$drdata[, c(1, 2)]\n    colnames(coords) <- c(\"x\", \"y\")\n    rownames(coords) <- attr(drResult$data, \"Labels\")\n    p <- emapplot(\n        x,\n        showCategory = showCategory,\n        coords = coords,\n        split = split,\n        pie = pie,\n        #with_edge = with_edge,\n        #cex_pie2axis = cex_pie2axis,\n        #group = group,\n        node_label = node_label,\n        ...\n    )\n    ## Set axis label according to the method parameter\n    p <- adj_axis(p = p, drResult = drResult)\n\n    p + theme_dr()\n}\n\n\n#' Get a distance matrix\n#'\n#' @param x enrichment result.\n#' @param showCategory number of enriched terms to display.\n#' @param split separate result by 'category' variable.\n#' @param pie proportion of clusters in the pie chart.\n#' @noRd\nbuild_dist <- function(x, showCategory, split = NULL, pie = NULL) {\n    sim = get_pairwise_sim(\n        x = x,\n        showCategory = showCategory,\n        split = split,\n        pie = pie\n    )\n\n    # ensure symmetry\n    if (!isSymmetric(sim)) {\n        sim <- (sim + t(sim)) / 2\n    }\n\n    # clamp to [0,1]\n    sim[is.na(sim)] <- 0\n    sim <- pmin(pmax(sim, 0), 1)\n\n    # avoid exact 1 for off-diagonal entries (some DR methods may fail)\n    eps <- .Machine$double.eps\n    diag(sim) <- 1\n    offdiag_idx <- row(sim) != col(sim)\n    sim[offdiag_idx & sim >= 1] <- 1 - eps\n\n    stats::as.dist(1 - sim)\n}\n\n\n#' Get a similarity matrix\n#'\n#' @param x enrichment result.\n#' @param showCategory number of enriched terms to display.\n#' @param split separate result by 'category' variable.\n#' @param pie proportion of clusters in the pie chart.\n#' @noRd\nget_pairwise_sim <- function(x, showCategory, split = NULL, pie = NULL) {\n    if (inherits(x, \"compareClusterResult\")) {\n        ## Optimized fortify call for large datasets\n        y <- fortify(\n            model = x,\n            showCategory = showCategory,\n            includeAll = TRUE,\n            split = split\n        )\n        y$Cluster <- sub(\"\\n.*\", \"\", y$Cluster)\n        \n        ## Optimized pie category preparation\n        pie_data <- prepare_pie_category(y, pie = pie)\n        keep <- rownames(pie_data)\n    } else {\n        n <- update_n(x, showCategory)\n        if (is.numeric(n)) {\n            keep <- seq_len(min(n, nrow(x@result)))\n        } else {\n            keep <- match(n, rownames(x@termsim))\n            keep <- keep[!is.na(keep)]\n        }\n    }\n    \n    if (length(keep) == 0) {\n        yulab_abort(\"no enriched term found (no rows selected by showCategory).\",\n                        class = \"no_terms_error\")\n    }\n    \n    ## Optimized termsim filling\n    fill_termsim(x, keep)\n}\n\n\n#' Adjust axis label according to the dimension reduction method\n#'\n#' @param p ggplot2 object\n#' @param drs dimension reduction result\n#' @noRd\nadj_axis <- function(p, drResult) {\n    title = NULL\n    eigenvalue <- drResult$eigenvalue\n    if (!is.null(eigenvalue) && length(eigenvalue) >= 2) {\n        total <- sum(eigenvalue)\n        if (total == 0) {\n            total <- 1\n        }\n\n        xlab = paste0(\n            \"Dimension1 (\",\n            format(100 * eigenvalue[1] / total, digits = 4), \n            \"%)\"\n        )\n        ylab = paste0(\n            \"Dimension2 (\",\n            format(100 * eigenvalue[2] / total, digits = 4), \n            \"%)\"\n        )\n    } else {\n        xlab = \"Dimension1\"\n        ylab = \"Dimension2\"\n        if (!is.null(drResult$stress)) {\n            title <- paste0(\"stress = \", drResult$stress)\n        }\n    }\n    p <- p + labs(x = xlab, y = ylab, title = title)\n    return(p)\n}\n\n#' Get the result of dimension reduction\n#'\n#' @param x enrichment result.\n#' @param showCategory number of enriched terms to display.\n#' @param split separate result by 'category' variable.\n#' @param pie proportion of clusters in the pie chart.\n#' @param drfun The function used for dimension reduction.\n#' @param dr.params list, the parameters of tidydr::dr.\n#' @importFrom rlang check_installed\n#' @noRd\nget_drResult <- function(\n    x,\n    showCategory,\n    split = NULL,\n    pie = NULL,\n    drfun,\n    dr.params\n) {\n    ## Input validation\n    check_input(x, arg_name = \"x\")\n    check_input(showCategory, arg_name = \"showCategory\")\n    \n    ## Optimized distance matrix building\n    distance_mat <- build_dist(\n        x = x,\n        showCategory = showCategory,\n        split = split,\n        pie = pie\n    )\n    \n    check_installed('tidydr', 'for `get_drResult()`')\n    \n    ## Optimized error handling\n    drResult <- tryCatch({\n        do.call(tidydr::dr, c(list(data = distance_mat, fun = drfun), dr.params))\n    }, error = function(e) {\n        yulab_warn(\"dimensionality reduction failed with provided drfun; falling back to stats::cmdscale\",\n                       class = \"dr_fallback_warning\")\n        \n        tryCatch({\n            tidydr::dr(distance_mat, stats::cmdscale, eig = TRUE)\n        }, error = function(e2) {\n            yulab_abort(\"dimensionality reduction failed (both provided method and fallback)\",\n                           class = \"dr_failure_error\")\n        })\n    })\n\n    if (is.null(drResult$drdata)) {\n        yulab_warn(\"Wrong drfun parameter or unsupported dimensionality reduction method; using stats::cmdscale\",\n                       class = \"dr_parameter_warning\")\n        drResult <- tidydr::dr(distance_mat, stats::cmdscale, eig = TRUE)\n    }\n    \n    return(drResult)\n}\n"
  },
  {
    "path": "R/treeplot.R",
    "content": "#' Tree plot for enrichment results\n#'\n#' Creates hierarchical tree visualization of enriched terms based on similarity\n#'\n#' @rdname treeplot\n#' @exportMethod treeplot\nsetMethod(\"treeplot\", signature(x = \"enrichResult\"), function(x, ...) {\n    treeplot_internal(x, size_var = \"Count\", ...)\n})\n\n\n#' @rdname treeplot\n#' @exportMethod treeplot\nsetMethod(\"treeplot\", signature(x = \"gseaResult\"), function(x, ...) {\n    treeplot_internal(x, size_var = \"setSize\", ...)\n})\n\n#' @rdname treeplot\n#' @exportMethod treeplot\nsetMethod(\"treeplot\", signature(x = \"compareClusterResult\"), function(x, ...) {\n    treeplot_compareCluster(x, ...)\n})\n\n\n#' @rdname treeplot\n#' @param showCategory number of enriched terms to display\n#' @param color variable to color nodes, e.g. 'p.adjust', 'pvalue', or 'qvalue'\n#' @param size_var variable for node size, e.g. 'Count' (for enrichResult) or 'setSize' (for gseaResult)\n#' @param nCluster number of clusters for tree cutting\n#' @param cluster_method hierarchical clustering method\n#' @param label_format wrap length for labels or custom formatting function\n#' @param fontsize_tiplab font size for tip labels\n#' @param fontsize_cladelab font size for clade labels\n#' @param group_color vector of colors for groups\n#' @param extend extend length for clade labels\n#' @param hilight whether to highlight clades\n#' @param align alignment for highlight rectangles\n#' @param hexpand expand x limits by amount of xrange * hexpand\n#' @param tiplab_offset offset for tip labels\n#' @param cladelab_offset offset for clade labels\n#' @return ggplot2 object representing the tree plot\n#' @importFrom ggtree ggtree geom_tiplab geom_tippoint groupClade geom_cladelab geom_hilight\n#' @importFrom ggplot2 scale_size_continuous guides guide_legend guide_colorbar\n#' @importFrom stats hclust cutree as.dist\ntreeplot_internal <- function(\n    x,\n    showCategory = 30,\n    color = \"p.adjust\",\n    size_var = c(\"Count\", \"setSize\"),\n    nCluster = 5,\n    cluster_method = \"ward.D\",\n    label_format = 30,\n    fontsize_tiplab = 4,\n    fontsize_cladelab = 4,\n    group_color = NULL,\n    extend = 0.3,\n    hilight = TRUE,\n    align = \"both\",\n    hexpand = 0.1,\n    tiplab_offset = 0.2,\n    cladelab_offset = 1\n) {\n    # Input validation\n    if (!inherits(x, c(\"enrichResult\", \"gseaResult\", \"compareClusterResult\"))) {\n        stop(\n            \"x must be an enrichResult, gseaResult, or compareClusterResult object\"\n        )\n    }\n\n    # Get selected categories\n    n <- update_n(x, showCategory)\n    if (is.numeric(n)) {\n        keep <- seq_len(n)\n    } else {\n        keep <- match(n, rownames(x@termsim))\n    }\n\n    if (length(keep) == 0) {\n        stop(\"no enriched term found...\")\n    }\n\n    # Prepare similarity matrix\n    termsim2 <- fill_termsim(x, keep)\n\n    # Hierarchical clustering\n    hc <- hclust(as.dist(1 - termsim2), method = cluster_method)\n    clus <- cutree(hc, nCluster)\n\n    # Prepare data for plotting\n    size_var <- intersect(size_var, colnames(x[]))[1]\n    if (is.na(size_var)) {\n        stop(\"size_var not found in enrichment result\")\n    }\n    \n    # Extract columns and ensure they exist\n    d <- x[keep, c(color, size_var)]\n    \n    # Handle case where columns are collapsed (e.g. tibble with duplicate columns)\n    if (ncol(d) == 1 && color == size_var) {\n        d <- data.frame(d, d)\n        names(d) <- c(color, size_var)\n    }\n\n    # Determine safe size column name\n    size_col <- \"size\"\n    if (color == \"size\") {\n        size_col <- \"size_value\"\n    }\n\n    # Rename size column\n    names(d)[2] <- size_col\n    \n    # Add label column from cluster names\n    d$label <- names(clus)\n    \n    # Select columns safely\n    d <- d[, c(\"label\", color, size_col)]\n\n    # Create tree plot\n    p <- create_tree_plot(\n        hc = hc,\n        clus = clus,\n        data = d,\n        label_format = label_format,\n        fontsize_tiplab = fontsize_tiplab,\n        fontsize_cladelab = fontsize_cladelab,\n        group_color = group_color,\n        extend = extend,\n        hilight = hilight,\n        align = align,\n        color_var = color,\n        size_var = size_col,\n        tiplab_offset = tiplab_offset,\n        cladelab_offset = cladelab_offset\n    )\n\n    # Add styling\n    p <- p +\n        scale_size_continuous(\n            name = size_var,\n            range = c(3, 8)\n        ) +\n        ggtree::hexpand(ratio = hexpand) +\n        guides(\n            size = guide_legend(order = 1),\n            color = guide_colorbar(order = 2)\n        )\n\n    return(p)\n}\n\n#' Tree plot for compareClusterResult objects\n#'\n#' @param x compareClusterResult object\n#' @param showCategory number of enriched terms to display\n#' @param color variable to color nodes\n#' @param nCluster number of clusters\n#' @param cluster_method hierarchical clustering method\n#' @param label_format label formatting\n#' @param fontsize_tiplab tip label font size\n#' @param fontsize_cladelab clade label font size\n#' @param group_color group colors\n#' @param extend extend length\n#' @param hilight whether to highlight clades\n#' @param align highlight alignment\n#' @param hexpand expand x limits\n#' @param tiplab_offset tip label offset\n#' @param cladelab_offset clade label offset\n#' @param pie proportion method for pie charts (\"equal\" or \"Count\")\n#' @param cluster_panel panel type for clusters (\"pie\", \"heatMap\", or \"dotplot\")\n#' @param legend_n number of legend items for pie charts\n#' @param colnames_angle angle for column names in heatmaps\n#' @importFrom ggtree gheatmap\n#' @importFrom scatterpie geom_scatterpie geom_scatterpie_legend\n#' @importFrom ggnewscale new_scale_fill new_scale_colour\n#' @noRd\ntreeplot_compareCluster <- function(\n    x,\n    showCategory = 30,\n    color = \"p.adjust\",\n    nCluster = 5,\n    cluster_method = \"ward.D\",\n    label_format = 30,\n    fontsize_tiplab = 4,\n    fontsize_cladelab = 4,\n    group_color = NULL,\n    extend = 0.3,\n    hilight = TRUE,\n    align = \"both\",\n    hexpand = 0.1,\n    tiplab_offset = 0.2,\n    cladelab_offset = 1,\n    pie = \"equal\",\n    cluster_panel = \"pie\",\n    legend_n = 3,\n    colnames_angle = 0\n) {\n    # Prepare data for compareClusterResult\n    y <- fortify(\n        x,\n        showCategory = showCategory,\n        includeAll = TRUE,\n        split = NULL\n    )\n    y$Cluster <- sub(\"\\n.*\", \"\", y$Cluster)\n\n    if (\"core_enrichment\" %in% colnames(y)) {\n        y$geneID <- y$core_enrichment\n    }\n\n    # Prepare cluster matrix\n    ID_Cluster_mat <- prepare_pie_category(y, pie = pie)\n\n    # Get selected categories\n    keep <- rownames(ID_Cluster_mat)\n\n    if (length(keep) == 0) {\n        stop(\"no enriched term found...\")\n    }\n\n    # Prepare similarity matrix\n    termsim2 <- fill_termsim(x, keep)\n\n    # Hierarchical clustering\n    hc <- hclust(as.dist(1 - termsim2), method = cluster_method)\n    clus <- cutree(hc, nCluster)\n\n    # Prepare data for plotting\n    merged_ggData <- merge_compareClusterResult(y)\n    rownames(merged_ggData) <- merged_ggData$Description\n    d <- data.frame(\n        label = names(clus),\n        count = merged_ggData[names(clus), \"Count\"]\n    )\n\n    # Create base tree plot\n    p <- create_tree_plot(\n        hc = hc,\n        clus = clus,\n        data = d,\n        label_format = label_format,\n        fontsize_tiplab = fontsize_tiplab,\n        fontsize_cladelab = fontsize_cladelab,\n        group_color = group_color,\n        extend = extend,\n        hilight = hilight,\n        align = align,\n        color_var = color,\n        tiplab_offset = tiplab_offset,\n        cladelab_offset = cladelab_offset,\n        add_tippoint = FALSE # Don't add tip points for compareCluster\n    )\n\n    # Add cluster panel based on type\n    p <- add_cluster_panel(\n        p = p,\n        cluster_panel = cluster_panel,\n        ID_Cluster_mat = ID_Cluster_mat,\n        x = x,\n        color = color,\n        legend_n = legend_n,\n        colnames_angle = colnames_angle,\n        hexpand = hexpand\n    )\n\n    return(p)\n}\n\n#' Add cluster panel to tree plot\n#'\n#' @param p tree plot\n#' @param cluster_panel panel type\n#' @param ID_Cluster_mat cluster matrix\n#' @param x compareClusterResult object\n#' @param color color variable\n#' @param legend_n legend items count\n#' @param colnames_angle column names angle\n#' @param hexpand expand ratio\n#' @importFrom rlang sym\n#' @noRd\nadd_cluster_panel <- function(\n    p,\n    cluster_panel,\n    ID_Cluster_mat,\n    x,\n    color,\n    legend_n,\n    colnames_angle,\n    hexpand\n) {\n    p_data <- as.data.frame(p$data)\n    p_data <- p_data[which(!is.na(p_data$label)), ]\n    rownames(p_data) <- p_data$label\n    p_data <- p_data[rownames(ID_Cluster_mat), ]\n\n    if (cluster_panel == \"pie\") {\n        # Add pie chart panel\n        ID_Cluster_mat$radius <- sqrt(p_data$count / sum(p_data$count))\n        ID_Cluster_mat$x <- p_data$x\n        ID_Cluster_mat$y <- p_data$y\n        ID_Cluster_mat$node <- p_data$node\n\n        p <- p +\n            ggnewscale::new_scale_fill() +\n            scatterpie::geom_scatterpie(\n                aes(x = .data$x, y = .data$y, r = .data$radius),\n                data = ID_Cluster_mat,\n                cols = colnames(ID_Cluster_mat)[1:(ncol(ID_Cluster_mat) - 4)],\n                color = NA\n            ) +\n            scatterpie::geom_scatterpie_legend(\n                ID_Cluster_mat$radius,\n                x = 0.8,\n                y = 0.1,\n                n = legend_n,\n                labeller = function(x) round(sum(p_data$count) * x^2)\n            ) +\n            labs(fill = \"Cluster\") +\n            coord_equal()\n    } else if (cluster_panel == \"heatMap\") {\n        # Add heatmap panel\n        heatMapData <- as.data.frame(x)\n        heatMapData$Cluster <- as.character(heatMapData$Cluster)\n        heatMapData <- heatMapData[\n            heatMapData$Cluster %in% colnames(ID_Cluster_mat),\n        ]\n        heatMapData <- heatMapData[\n            heatMapData$Description %in% rownames(ID_Cluster_mat),\n        ]\n\n        for (i in seq_len(nrow(heatMapData))) {\n            ID_Cluster_mat[\n                heatMapData[i, \"Description\"],\n                heatMapData[i, \"Cluster\"]\n            ] <- heatMapData[i, color]\n        }\n\n        p <- p +\n            ggnewscale::new_scale_fill() +\n            ggtree::gheatmap(\n                ID_Cluster_mat,\n                colnames_angle = colnames_angle,\n                width = 0.5\n            ) +\n            set_enrichplot_color(\n                type = \"fill\",\n                transform = \"log10\",\n                name = color\n            )\n    } else if (cluster_panel == \"dotplot\") {\n        # Add dotplot panel\n        dotdata <- as.data.frame(x)\n        pData <- as.data.frame(p$data)\n        paths <- pData$label[order(pData$y, decreasing = TRUE)]\n        paths <- paths[!is.na(paths)]\n        dotdata <- dotdata[dotdata$Description %in% paths, ]\n        dotdata <- dplyr::select(dotdata, .data$Description, dplyr::everything())\n\n        p <- p +\n            ggnewscale::new_scale_colour() +\n            ggtreeExtra::geom_fruit(\n                data = dotdata,\n                geom = geom_point,\n                mapping = aes(\n                    x = .data$Cluster,\n                    y = .data$Description,\n                    size = .data$Count,\n                    color = .data[[color]]\n                ),\n                pwidth = 0.06 * ncol(ID_Cluster_mat),\n                axis.params = list(\n                    axis = \"x\",\n                    text.size = 3,\n                    line.alpha = 0,\n                    text.angle = colnames_angle\n                )\n            ) +\n            set_enrichplot_color(transform = \"log10\", name = color)\n    }\n\n    return(p + ggtree::hexpand(ratio = hexpand))\n}\n\n#' Create tree plot from clustering results\n#'\n#' @param hc hierarchical clustering result\n#' @param clus cluster assignments\n#' @param data node data\n#' @param label_format label formatting\n#' @param fontsize_tiplab tip label font size\n#' @param fontsize_cladelab clade label font size\n#' @param group_color group colors\n#' @param extend extend length\n#' @param hilight whether to highlight\n#' @param align highlight alignment\n#' @param color_var color variable name\n#' @param tiplab_offset tip label offset\n#' @param cladelab_offset clade label offset\n#' @param add_tippoint whether to add tip points (default: TRUE)\n#' @noRd\n#' @importFrom ggfun %<+%\ncreate_tree_plot <- function(\n    hc,\n    clus,\n    data,\n    label_format,\n    fontsize_tiplab,\n    fontsize_cladelab,\n    group_color,\n    extend,\n    hilight,\n    align = 'left',\n    color_var,\n    size_var = 'size',\n    tiplab_offset = 0.2,\n    cladelab_offset,\n    add_tippoint = TRUE\n) {\n    # Set colors\n    if (is.null(group_color)) {\n        n_clusters <- length(unique(clus))\n        group_color <- scales::hue_pal()(n_clusters)\n    }\n\n    # Create base tree\n    p <- ggtree(hc, hang = -1, branch.length = \"none\")\n\n    # Group nodes\n    dat <- data.frame(\n        name = names(clus),\n        cls = paste0(\"cluster_\", as.numeric(clus))\n    )\n    grp <- apply(table(dat), 2, function(x) names(x[x == 1]))\n    clades <- vapply(grp, \\(nodes) ggtree::MRCA(p, nodes), numeric(1))\n    p <- groupClade(p, clades, \"group\") +\n        aes(color = .data$group) +\n        scale_color_manual(\n            values = c(group_color, \"white\"),\n            breaks = names(clades)\n        )\n\n    # Add tip points and labels\n    p <- p %<+% data\n\n    # Add clade labels and highlights\n    if (hilight) {\n        p <- add_clade_labels(\n            p,\n            clades,\n            label_format,\n            fontsize_cladelab,\n            group_color,\n            extend,\n            align,\n            offset = cladelab_offset\n        )\n    }\n\n    if (add_tippoint) {\n        p <- p +\n            ggnewscale::new_scale_colour() +\n            geom_tippoint(aes(\n                color = .data[[color_var]],\n                size = .data[[size_var]]\n            ))\n        if (color_var %in% c(\"pvalue\", \"qvalue\", \"p.adjust\")) {\n            p <- p + set_enrichplot_color(transform = 'log10')\n        } else {\n            p <- p +\n                set_enrichplot_color(\n                    colors = rev(get_enrichplot_color(3)),\n                )\n        }\n    }\n\n    p <- p +\n        geom_tiplab(\n            offset = tiplab_offset,\n            hjust = 0,\n            size = fontsize_tiplab\n        )\n\n    return(p)\n}\n\n\n#' Add clade labels and highlights to tree plot\n#'\n#' @param p tree plot\n#' @param clades clade definitions\n#' @param label_format label formatting\n#' @param fontsize font size\n#' @param group_color group colors\n#' @param extend extend length\n#' @param align highlight alignment\n#' @importFrom ggplot2 scale_fill_manual\n#' @noRd\nadd_clade_labels <- function(\n    p,\n    clades,\n    label_format,\n    fontsize,\n    group_color,\n    extend,\n    align,\n    offset\n) {\n    # Prepare clade label data\n    df <- data.frame(\n        node = as.numeric(clades),\n        labels = names(clades),\n        cluster = factor(names(clades))\n    )\n\n    # Get the tree data to access tip labels\n    pdata <- as.data.frame(p$data)\n    pdata <- pdata[!is.na(pdata$label), ]\n\n    # Create the required data structure for get_wordcloud\n    wordcloud_data <- data.frame(\n        name = pdata$label,\n        color2 = pdata$group\n    )\n\n    # Generate meaningful cluster labels from tip labels\n    cluster_labels <- sapply(names(clades), function(cluster_name) {\n        get_wordcloud(cluster_name, wordcloud_data, nWords = 4)\n    })\n\n    df$labels <- cluster_labels\n\n    # Apply label formatting\n    label_func <- default_labeller(label_format)\n    if (is.function(label_format)) {\n        label_func <- label_format\n    }\n    df$labels <- label_func(df$labels)\n\n    df$color <- group_color\n\n    # Add clade labels and highlights\n    p <- p +\n        ggnewscale::new_scale_colour() +\n        geom_cladelab(\n            data = df,\n            mapping = aes(\n                node = !!sym('node'),\n                label = !!sym('labels'),\n                color = !!sym('cluster')\n            ),\n            textcolor = \"black\",\n            extend = extend,\n            show.legend = FALSE,\n            fontsize = fontsize,\n            offset = offset\n        ) +\n        scale_color_manual(values = group_color, guide = 'none') +\n        geom_hilight(\n            data = df,\n            mapping = aes(node = !!sym('node'), fill = !!sym('cluster')),\n            show.legend = FALSE,\n            align = align\n        ) +\n        scale_fill_manual(values = group_color, guide = 'none')\n\n    return(p)\n}\n\n\n#' Fill the upper triangular matrix completely\n#'\n#' @param x enrichment result\n#' @param keep selected categories\n#' @return filled similarity matrix\n#' @noRd\nfill_termsim <- function(x, keep) {\n    termsim <- x@termsim[keep, keep]\n    termsim[which(is.na(termsim))] <- 0\n    termsim2 <- termsim + t(termsim)\n    diag(termsim2) <- 1\n    return(termsim2)\n}\n"
  },
  {
    "path": "R/upsetplot.R",
    "content": "#' Upsetplot\n#'\n#' Upsetplot\n#'\n#' @rdname upsetplot-methods\n#' @aliases upsetplot,enrichResult,ANY-method\n#' @param n number of categories to be plotted\n#' @param ... additional parameters\n#' @author Guangchuang Yu\n#' @exportMethod upsetplot\n#' @examples\n#' library(DOSE)\n#' data(geneList)\n#' de <- names(geneList)[1:100]\n#' x <- enrichDO(de)\n#' upsetplot(x, 8)\nsetMethod(\"upsetplot\", signature(x=\"enrichResult\"),\n          function(x, n=10, ...) {\n              upsetplot.enrichResult(x, n, ...)\n          })\n\n#' @rdname upsetplot-methods\n#' @aliases upsetplot,gseaResult\n#' @exportMethod upsetplot\nsetMethod(\"upsetplot\", signature(x=\"gseaResult\"),\n          function(x, n=10, ...) {\n              upsetplot.gseaResult(x, n, ...)\n          })\n\n\n#' @importFrom rlang check_installed\nupsetplot.enrichResult <- function(x, n=10, ...) {\n    df <- as.data.frame(x)\n    id <- df$ID[1:n]\n    des <- df$Description[1:n]\n    glist <- geneInCategory(x)[id]\n    names(glist) <- des\n    ## g <- unique(unlist(glist))\n\n\n    ## dat <- matrix(0, nrow=length(g), ncol=length(id))\n    ## rownames(dat) <- g\n    ## for (i in 1:length(id)) {\n    ##     dat[glist[[i]], i] <- 1\n    ## }\n    ## colnames(dat) <- des\n\n    ## ## cols <- ggtree:::color_scale(\"red\", \"blue\")\n    ## ## pv <- df$pvalue[1:n]\n    ## ## idx <- sapply(pv, function(p) DOSE:::getIdx(p, min(pv), max(pv)))\n\n    ## ## sets.bar.color = cols[idx],\n\n    ## ## UpSetR <- \"UpSetR\"\n    ## ## require(UpSetR, character.only = TRUE)\n    ## ## upset <- eval(parse(text=\"upset\"))\n\n    ## upsetR::upset(as.data.frame(dat), nsets=n, ...)\n    d <- list2df(glist)\n    check_installed('tibble', 'for `upsetplot()`.')\n    check_installed('ggupset', 'for `upsetplot()`.')\n    res <- tibble::tibble(Description = split(d[,1], d[,2]))\n    ggplot(res, aes(x = .data$Description)) + geom_bar() +\n        theme_dose(font.size = 12) +\n\txlab(NULL) + ylab(NULL) +\n\tggupset::scale_x_upset(order_by = \"freq\")\n}\n\n#' @importFrom ggplot2 geom_violin\n#' @importFrom ggplot2 geom_jitter\n#' @importFrom rlang check_installed\nupsetplot.gseaResult <- function(x, n = 10, type = \"boxplot\", ...) {\n    n <- update_n(x, n)\n    geneSets <- extract_geneSets(x, n)\n\n    ## foldChange <- fc_readable(x, x@geneList)\n    d <- list2df(geneSets)\n\n    category <- split(d[,1], d[, 2])\n    check_installed('tibble', 'for `upsetplot()`.')\n    y <- tibble::tibble(Description = category,\n                      gene = names(category),\n                      foldChange = x@geneList[names(category)])\n\n    if (type == \"boxplot\") {\n        ly_dist <- geom_boxplot()\n    } else {\n        ly_dist <- geom_violin()\n    }\n    \n    check_installed('ggupset', 'for `upsetplot()`.')\n    ggplot(y, aes(x = .data$Description, y = .data$foldChange)) +\n        ly_dist +\n        geom_jitter(width = .2, alpha = .6) +\n        theme_dose(font.size = 12) +\n        xlab(NULL) + ylab(NULL) +\n        ggupset::scale_x_upset(order_by = \"degree\")\n}\n\n## @rdname upsetplot-methods\n## @aliases upsetplot,compareClusterResult\n## @exportMethod upsetplot\n#setMethod(\"upsetplot\", signature(x=\"compareClusterResult\"),\n#          function(x, n=10, ...) {\n#              upsetplot.compareClusterResult(x, n, ...)\n#          })\n\n\nupsetplot.compareClusterResult <- function(x, n, ...) {\n    x <- append_intersect(x)\n\n    ## ggplot(x, aes(-10*log10(p.adjust), Description)) + geom_point() + facet_grid(set~., scales=\"free\")\n\n    ggplot(x, aes(x = .data$Cluster, y = .data$Description), showCategory=n) + \n        geom_point(aes(size = -10 * log10(.data$p.adjust), color = .data$Cluster)) + \n        facet_grid(intersect ~ ., scales = \"free\", space = 'free') + guides(color = \"none\") +\n        theme_dose(font.size = 12) +\n        theme(strip.text = element_text(size = 14)) +\n        xlab(NULL) + ylab(NULL) \n}\n\n"
  },
  {
    "path": "R/volplot.R",
    "content": "#' @rdname volplot\n#' @exportMethod volplot\n#' @author Guangchuang Yu\nsetMethod(\"volplot\", signature(x = \"enrichResult\"),\n        function(x, color = \"zScore\", \n                xintercept = 1, yintercept = 2,  \n                showCategory = 5, label_format = 30,\n                ...) {\n            volplot.enrichResult(x = x, color = color, \n                xintercept = xintercept, yintercept = yintercept,\n                showCategory = showCategory, label_format = label_format, \n                ...)\n        })\n\n#' @rdname volplot\n#' @param font.size font size for `theme_dose()`\n#' @param size font size to label selected categories specified by showCategory\nvolplot.enrichResult <- function(x, color = \"zScore\", \n                xintercept = 1, yintercept = 2, \n                showCategory=5, label_format = 30, \n                font.size=12, size = 5) {\n\n    if (yintercept < 1) yintercept = -log10(yintercept)\n\n    p <- ggplot(x@result, aes(x=log2(.data$FoldEnrichment), y= -log10(.data$p.adjust))) + \n        geom_point(aes(color=.data[[color]])) +\n        geom_hline(yintercept = yintercept, lty='dashed') +\n        geom_vline(xintercept = xintercept, lty='dashed')\n\n    p <- p + set_enrichplot_color(type = \"color\", reverse = FALSE) +\n        theme_dose(font.size) \n\n    if (is.numeric(showCategory)) {\n        topN <- showCategory\n        d <- dplyr::arrange(x@result, dplyr::desc(.data[[color]]))\n        showCategory <- d$Description[1:topN]\n    }\n\n    label_func <- .label_format(label_format)\n    p <- p + ggrepel::geom_text_repel(aes(label=label_func(.data$Description)), \n                    data = function(d) dplyr::filter(d, .data$Description %in% showCategory), \n                    size = size\n        ) \n        \n    p <- p + labs(x=bquote(paste(log[2], \"(FoldEnrichment)\")),\n                y = bquote(paste(-log[10], \"(p.adjust)\"))\n            )\n    \n    return(p)\n}"
  },
  {
    "path": "R/wordcloud.R",
    "content": "#' Use wordcloud algorithm to get group tags\n#'\n#' @param cluster a cluster name\n#' @param node_data the data section of the ggplot object,\n#' which contains clustering information.\n#' @param nWords the number of words in the cluster tags\n#' @importFrom utils head\n#' @noRd\nget_wordcloud <- function(cluster, node_data, nWords = 4) {\n    cluster_terms <- node_data$name[node_data$color2 == cluster]\n\n    if (length(cluster_terms) == 0) {\n        return(cluster)\n    }\n\n    words <- cluster_terms |>\n        tolower() |>\n        gsub(\" in \", \" \", x = _) |>\n        gsub(\" [0-9]+ \", \" \", x = _) |>\n        gsub(\"^[0-9]+ \", \"\", x = _) |>\n        gsub(\" [0-9]+$\", \"\", x = _) |>\n        gsub(\" [a-z] \", \" \", x = _) |>\n        gsub(\"^[a-z] \", \"\", x = _) |>\n        gsub(\" [a-z]$\", \"\", x = _) |>\n        gsub(\" / \", \" \", x = _) |>\n        gsub(\" and \", \" \", x = _) |>\n        gsub(\" of \", \" \", x = _) |>\n        gsub(\",\", \" \", x = _) |>\n        gsub(\" - \", \" \", x = _) |>\n        gsub(\"\\\\s+\", \" \", x = _) |> # multiple spaces to single space\n        trimws() # remove leading/trailing whitespace\n\n    # Split into words and calculate frequencies\n    all_words <- unlist(strsplit(words, \"\\\\s+\"))\n\n    if (length(all_words) == 0) {\n        return(cluster)\n    }\n\n    word_freq <- table(all_words)\n    word_freq <- word_freq[order(word_freq, decreasing = TRUE)]\n\n    # Remove common stop words\n    stop_words <- c(\n        \"the\",\n        \"and\",\n        \"for\",\n        \"with\",\n        \"via\",\n        \"by\",\n        \"to\",\n        \"a\",\n        \"an\",\n        \"in\",\n        \"of\",\n        \"on\",\n        \"at\"\n    )\n    meaningful_words <- names(word_freq)[\n        !tolower(names(word_freq)) %in% stop_words\n    ]\n\n    # Get top nWords meaningful words\n    if (length(meaningful_words) > 0) {\n        top_words <- head(meaningful_words, nWords)\n\n        # Consider word position for ordering (optional enhancement)\n        word_positions <- calculate_word_positions(cluster_terms, top_words)\n        if (!is.null(word_positions)) {\n            top_words <- word_positions\n        }\n\n        return(paste(top_words, collapse = \" \"))\n    } else {\n        # Fallback: use most frequent words regardless\n        top_words <- head(names(word_freq), nWords)\n        return(paste(top_words, collapse = \" \"))\n    }\n}\n\n\n#' Calculate word positions to improve label ordering\n#'\n#' @param terms vector of terms\n#' @param candidate_words candidate words for the label\n#' @return ordered words based on position\n#' @noRd\ncalculate_word_positions <- function(terms, candidate_words) {\n    if (length(terms) == 0 || length(candidate_words) == 0) {\n        return(NULL)\n    }\n\n    # Split all terms into words\n    all_term_words <- strsplit(tolower(terms), \"\\\\s+\")\n\n    # Calculate average position for each candidate word\n    word_ranks <- list()\n\n    for (word in candidate_words) {\n        positions <- c()\n        for (term_words in all_term_words) {\n            word_idx <- which(term_words == tolower(word))\n            if (length(word_idx) > 0) {\n                positions <- c(positions, word_idx)\n            }\n        }\n        if (length(positions) > 0) {\n            word_ranks[[word]] <- mean(positions)\n        } else {\n            word_ranks[[word]] <- Inf # Word not found in any term\n        }\n    }\n\n    # Order words by their average position\n    if (length(word_ranks) > 0) {\n        sorted_words <- names(sort(unlist(word_ranks)))\n        return(sorted_words)\n    }\n\n    return(NULL)\n}\n"
  },
  {
    "path": "R/zzz.R",
    "content": "#' @importFrom yulab.utils yulab_msg\n.onAttach <- function(libname, pkgname) {\n    options(check.tbl_tree.verbose = FALSE)\n    packageStartupMessage(yulab.utils::yulab_msg(pkgname))\n}\n\n\n"
  },
  {
    "path": "README.Rmd",
    "content": "---\noutput:\n  md_document:\n    variant: gfm\nhtml_preview: false\n---\n\n<!-- README.md is generated from README.Rmd. Please edit that file -->\n\n\n#  `r packageDescription(\"enrichplot\")$Title`\n\n```{r echo=FALSE, results=\"hide\", message=FALSE}\nlibrary(\"badger\")\n```\n\n\n\n`r badge_bioc_release(\"enrichplot\", \"green\")`\n`r badge_devel(\"guangchuangyu/enrichplot\", \"green\")`\n[![Bioc](http://www.bioconductor.org/shields/years-in-bioc/enrichplot.svg)](https://www.bioconductor.org/packages/devel/bioc/html/enrichplot.html#since)\n\n`r badge_download_bioc(\"enrichplot\")`\n`r badge_bioc_download(\"enrichplot\", \"total\", \"blue\")`\n`r badge_bioc_download(\"enrichplot\", \"month\", \"blue\")`\n\n\n[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)\n[![platform](http://www.bioconductor.org/shields/availability/devel/enrichplot.svg)](https://www.bioconductor.org/packages/devel/bioc/html/enrichplot.html#archives)\n[![Build Status](http://www.bioconductor.org/shields/build/devel/bioc/treeio.svg)](https://bioconductor.org/checkResults/devel/bioc-LATEST/treeio/)\n[![Last-changedate](https://img.shields.io/badge/last%20change-`r gsub('-', '--', Sys.Date())`-green.svg)](https://github.com/GuangchuangYu/treeio/commits/master)\n\n\n```{r comment=\"\", echo=FALSE, results='asis'}\ncat(packageDescription('enrichplot')$Description)\n```\n\n\nFor details, please visit <https://yulab-smu.top/biomedical-knowledge-mining-book/enrichplot.html>.\n\n\n## :writing_hand: Authors\n\n\nGuangchuang YU <https://yulab-smu.top>\n\n\nSchool of Basic Medical Sciences, Southern Medical University\n\n\n## :arrow_double_down: Installation\n\n\nGet the released version from Bioconductor:\n\n```r\n## try http:// if https:// URLs are not supported\nif (!requireNamespace(\"BiocManager\", quietly=TRUE))\n    install.packages(\"BiocManager\")\n## BiocManager::install(\"BiocUpgrade\") ## you may need this\nBiocManager::install(\"enrichplot\")\n```\n\nOr the development version from github:\n\n```r\n## install.packages(\"remotes\")\nremotes::install_github(\"YuLab-SMU/enrichplot\")\n\n## or\n## install.packages(\"yulab.utils\")\nyulab.utils::install_zip_gh(\"YuLab-SMU/enrichplot\")\n```\n\n\n## :sparkling_heart: Contributing\n\nWe welcome any contributions! By participating in this project you agree to\nabide by the terms outlined in the [Contributor Code of Conduct](CONDUCT.md).\n\n"
  },
  {
    "path": "README.md",
    "content": "<!-- README.md is generated from README.Rmd. Please edit that file -->\n\n# Visualization of Functional Enrichment Result\n\n[![](https://img.shields.io/badge/release%20version-1.30.5-green.svg)](https://www.bioconductor.org/packages/enrichplot)\n[![](https://img.shields.io/badge/devel%20version-1.31.5-green.svg)](https://github.com/guangchuangyu/enrichplot)\n[![Bioc](http://www.bioconductor.org/shields/years-in-bioc/enrichplot.svg)](https://www.bioconductor.org/packages/devel/bioc/html/enrichplot.html#since)\n\n[![download](http://www.bioconductor.org/shields/downloads/release/enrichplot.svg)](https://bioconductor.org/packages/stats/bioc/enrichplot)\n[![](https://img.shields.io/badge/download-1256962/total-blue.svg)](https://bioconductor.org/packages/stats/bioc/enrichplot)\n[![](https://img.shields.io/badge/download-38757/month-blue.svg)](https://bioconductor.org/packages/stats/bioc/enrichplot)\n\n[![Project Status: Active - The project has reached a stable, usable\nstate and is being actively\ndeveloped.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)\n[![platform](http://www.bioconductor.org/shields/availability/devel/enrichplot.svg)](https://www.bioconductor.org/packages/devel/bioc/html/enrichplot.html#archives)\n[![Build\nStatus](http://www.bioconductor.org/shields/build/devel/bioc/treeio.svg)](https://bioconductor.org/checkResults/devel/bioc-LATEST/treeio/)\n[![Last-changedate](https://img.shields.io/badge/last%20change-2026--04--24-green.svg)](https://github.com/GuangchuangYu/treeio/commits/master)\n\nThe ‘enrichplot’ package provides visualization methods for interpreting\nfunctional enrichment results from ORA or GSEA analyses. It is designed\nto work with the ‘clusterProfiler’ ecosystem and builds on ‘ggplot2’ for\nflexible and extensible graphics.\n\nFor details, please visit\n<https://yulab-smu.top/biomedical-knowledge-mining-book/enrichplot.html>.\n\n## :writing_hand: Authors\n\nGuangchuang YU <https://yulab-smu.top>\n\nSchool of Basic Medical Sciences, Southern Medical University\n\n## :arrow_double_down: Installation\n\nGet the released version from Bioconductor:\n\n``` r\n## try http:// if https:// URLs are not supported\nif (!requireNamespace(\"BiocManager\", quietly=TRUE))\n    install.packages(\"BiocManager\")\n## BiocManager::install(\"BiocUpgrade\") ## you may need this\nBiocManager::install(\"enrichplot\")\n```\n\nOr the development version from github:\n\n``` r\n## install.packages(\"remotes\")\nremotes::install_github(\"YuLab-SMU/enrichplot\")\n\n## or\n## install.packages(\"yulab.utils\")\nyulab.utils::install_zip_gh(\"YuLab-SMU/enrichplot\")\n```\n\n## :sparkling_heart: Contributing\n\nWe welcome any contributions! By participating in this project you agree\nto abide by the terms outlined in the [Contributor Code of\nConduct](CONDUCT.md).\n"
  },
  {
    "path": "TODO.md",
    "content": "# TODO LIST\n\n+ [x] manhattan plot for enriched result\n  - figure 1 of <https://f1000research.com/articles/9-709>\n+ [ ] Circos plot for expression prifile and pathway annotation\n  - Fig 2 of <https://doi.org/10.1038/s41467-020-14802-2>\n  - maybe a cartisian coordination version, i.e. a heatmap with a dot table to indicate the pathways belong.\n+ [x] plot enriched terms as a tree\n  - hc(1-sim), where sim is calculated by GOSemSim, and visualize by ggtree\n  - label clade with representative words\n+ [ ] plot gene expression profile by PCA (or other methods) and label clusters with representative words\n"
  },
  {
    "path": "enrichplot.Rproj",
    "content": "Version: 1.0\n\nRestoreWorkspace: No\nSaveWorkspace: No\nAlwaysSaveHistory: Default\n\nEnableCodeIndexing: Yes\nUseSpacesForTab: Yes\nNumSpacesForTab: 4\nEncoding: UTF-8\n\nRnwWeave: knitr\nLaTeX: pdfLaTeX\n\nAutoAppendNewline: Yes\nStripTrailingWhitespace: Yes\n\nBuildType: Package\nPackageUseDevtools: Yes\nPackageInstallArgs: --no-multiarch --with-keep.source\nPackageRoxygenize: rd,collate,namespace\n"
  },
  {
    "path": "man/as.data.frame.compareClusterResult.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/data_utils.R\n\\name{as.data.frame.compareClusterResult}\n\\alias{as.data.frame.compareClusterResult}\n\\title{Convert compareClusterResult to data frame}\n\\usage{\n\\method{as.data.frame}{compareClusterResult}(x, ...)\n}\n\\arguments{\n\\item{x}{compareClusterResult object}\n\n\\item{...}{additional parameters}\n}\n\\value{\ndata frame\n}\n\\description{\nConvert compareClusterResult to data frame\n}\n"
  },
  {
    "path": "man/autofacet.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/plot_utils.R\n\\name{autofacet}\n\\alias{autofacet}\n\\title{Plotting utility functions for enrichplot package}\n\\usage{\nautofacet(by = \"row\", scales = \"free\", levels = NULL)\n}\n\\arguments{\n\\item{by}{one of 'row' or 'column'}\n\n\\item{scales}{whether 'fixed' or 'free'}\n\n\\item{levels}{set facet levels}\n}\n\\value{\na ggplot object\n}\n\\description{\nThis file contains plotting and visualization helper functions for enrichplot\nAutomatically split barplot or dotplot into several facets\n}\n"
  },
  {
    "path": "man/barplot.enrichResult.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/barplot.R\n\\name{barplot.enrichResult}\n\\alias{barplot.enrichResult}\n\\title{barplot}\n\\usage{\n\\method{barplot}{enrichResult}(\n  height,\n  x = \"Count\",\n  color = \"p.adjust\",\n  showCategory = 8,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n}\n\\arguments{\n\\item{height}{enrichResult object}\n\n\\item{x}{one of 'Count' and 'GeneRatio'}\n\n\\item{color}{one of 'pvalue', 'p.adjust' and 'qvalue'}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{font.size}{font size}\n\n\\item{title}{plot title}\n\n\\item{label_format}{a numeric value sets wrap length, alternatively a\ncustom function to format axis labels.\nby default wraps names longer than 30 characters}\n\n\\item{...}{additional parameters}\n}\n\\value{\nggplot object\n}\n\\description{\nBarplot of enrichResult\n}\n\\details{\nBarplot of enrichResult\n}\n\\examples{\nlibrary(DOSE)\ndata(geneList)\nde <- names(geneList)[1:100]\nx <- enrichDO(de)\nbarplot(x)\n# use `showCategory` to select the displayed terms. It can be a number of a vector of terms.\nbarplot(x, showCategory = 10)\ncategories <- c(\"urinary bladder cancer\", \"bronchiolitis obliterans\",\n               \"aortic aneurysm\", \"esophageal cancer\")\nbarplot(x, showCategory = categories)\n}\n"
  },
  {
    "path": "man/cnetplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/cnetplot.R\n\\name{cnetplot.enrichResult}\n\\alias{cnetplot.enrichResult}\n\\alias{cnetplot.gseaResult}\n\\alias{cnetplot.compareClusterResult}\n\\title{Category-Gene-Network Plot}\n\\usage{\n\\method{cnetplot}{enrichResult}(\n  x,\n  layout = igraph::layout_with_kk,\n  showCategory = 5,\n  color_category = \"#E5C494\",\n  size_category = 1,\n  color_item = \"#B3B3B3\",\n  size_item = 1,\n  color_edge = \"grey\",\n  size_edge = 0.5,\n  categorySizeBy = ~itemNum,\n  node_label = \"all\",\n  foldChange = NULL,\n  fc_threshold = NULL,\n  hilight = \"none\",\n  hilight_alpha = 0.3,\n  ...\n)\n\n\\method{cnetplot}{gseaResult}(\n  x,\n  layout = igraph::layout_with_kk,\n  showCategory = 5,\n  color_category = \"#E5C494\",\n  size_category = 1,\n  color_item = \"#B3B3B3\",\n  size_item = 1,\n  color_edge = \"grey\",\n  size_edge = 0.5,\n  categorySizeBy = ~itemNum,\n  node_label = \"all\",\n  foldChange = NULL,\n  fc_threshold = NULL,\n  hilight = \"none\",\n  hilight_alpha = 0.3,\n  ...\n)\n\n\\method{cnetplot}{compareClusterResult}(\n  x,\n  layout = igraph::layout_with_kk,\n  showCategory = 5,\n  color_category = \"#E5C494\",\n  size_category = 1,\n  color_item = \"#B3B3B3\",\n  size_item = 1,\n  color_edge = \"grey\",\n  size_edge = 0.5,\n  categorySizeBy = ~itemNum,\n  node_label = \"all\",\n  foldChange = NULL,\n  fc_threshold = NULL,\n  hilight = \"none\",\n  hilight_alpha = 0.3,\n  pie = \"equal\",\n  split = NULL,\n  includeAll = TRUE,\n  ...\n)\n}\n\\arguments{\n\\item{x}{input object}\n\n\\item{layout}{network layout}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{color_category}{color of category nodes}\n\n\\item{size_category}{relative size of the category nodes}\n\n\\item{color_item}{color of item nodes}\n\n\\item{size_item}{relative size of the item nodes (e.g., genes)}\n\n\\item{color_edge}{color of edge}\n\n\\item{size_edge}{relative size of edge}\n\n\\item{categorySizeBy}{An expression (e.g., \\code{itemNum}, \\code{p.adjust}) or a formula\n(e.g., \\code{~ -log10(p.adjust)}) to set the category node size. For\n\\code{compareClusterResult}, this controls the category pie size.}\n\n\\item{node_label}{one of 'all', 'none', 'category', 'item', 'exclusive' or 'share'.\n'exclusive' labels genes that uniquely belong to categories; 'share' labels genes that are shared between categories.}\n\n\\item{foldChange}{numeric values to color the item (e.g., fold change of gene expression values)}\n\n\\item{fc_threshold}{threshold for filtering genes by absolute fold change (e.g., fc_threshold = 1 keeps only genes with |foldChange| > 1).}\n\n\\item{hilight}{selected categories to be highlighted}\n\n\\item{hilight_alpha}{transparency value for non-highlighted items}\n\n\\item{...}{additional parameters}\n\n\\item{pie}{one of 'equal' or 'Count' to set the slice ratio of the pies}\n\n\\item{split}{apply \\code{showCategory} to each category specified by \\code{split} for\n\\code{compareClusterResult}, e.g. \\code{ONTOLOGY}, \\code{category} or \\code{intersect}.}\n\n\\item{includeAll}{logical value passed to \\code{fortify()} when selecting terms\nfrom a \\code{compareClusterResult}.}\n}\n\\description{\nCategory-gene-network plot\n}\n\\seealso{\n\\link[ggtangle:cnetplot]{cnetplot}\n}\n"
  },
  {
    "path": "man/color_palette.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/color_utils.R\n\\name{color_palette}\n\\alias{color_palette}\n\\title{Create color palette for continuous data}\n\\usage{\ncolor_palette(colors)\n}\n\\arguments{\n\\item{colors}{colors of length >=2}\n}\n\\value{\ncolor vector\n}\n\\description{\nCreate color palette for continuous data\n}\n\\examples{\ncolor_palette(c(\"red\", \"yellow\", \"green\"))\n}\n\\author{\nguangchuang yu\n}\n"
  },
  {
    "path": "man/dotplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/dotplot.R\n\\name{dotplot}\n\\alias{dotplot}\n\\alias{dotplot,enrichResult-method}\n\\alias{dotplot,gseaResult-method}\n\\alias{dotplot,compareClusterResult-method}\n\\alias{dotplot,compareClusterResult,ANY-method}\n\\alias{dotplot,enrichResultList-method}\n\\alias{dotplot,enrichResultList,ANY-method}\n\\alias{dotplot,gseaResultList-method}\n\\alias{dotplot,gseaResultList,ANY-method}\n\\alias{dotplot.enrichResult}\n\\alias{dotplot.compareClusterResult}\n\\title{dotplot}\n\\usage{\ndotplot(object, ...)\n\n\\S4method{dotplot}{enrichResult}(\n  object,\n  x = \"GeneRatio\",\n  color = \"p.adjust\",\n  showCategory = 10,\n  size = NULL,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  orderBy = \"x\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{dotplot}{gseaResult}(\n  object,\n  x = \"GeneRatio\",\n  color = \"p.adjust\",\n  showCategory = 10,\n  size = NULL,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  orderBy = \"x\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{dotplot}{compareClusterResult}(\n  object,\n  x = \"Cluster\",\n  color = \"p.adjust\",\n  showCategory = 5,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  by = \"geneRatio\",\n  size = NULL,\n  includeAll = TRUE,\n  label_format = 30,\n  ...\n)\n\n\\S4method{dotplot}{enrichResultList}(\n  object,\n  x = \"GeneRatio\",\n  color = \"p.adjust\",\n  showCategory = 10,\n  size = NULL,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  orderBy = \"x\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{dotplot}{gseaResultList}(\n  object,\n  x = \"GeneRatio\",\n  color = \"p.adjust\",\n  showCategory = 10,\n  size = NULL,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  orderBy = \"x\",\n  label_format = 30,\n  ...\n)\n\ndotplot.enrichResult(\n  object,\n  x = \"geneRatio\",\n  color = \"p.adjust\",\n  showCategory = 10,\n  size = NULL,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  orderBy = \"x\",\n  label_format = 30,\n  decreasing = TRUE\n)\n\ndotplot.compareClusterResult(\n  object,\n  x = \"Cluster\",\n  colorBy = \"p.adjust\",\n  showCategory = 5,\n  by = \"geneRatio\",\n  size = \"geneRatio\",\n  split = NULL,\n  includeAll = TRUE,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  group = FALSE,\n  shape = FALSE,\n  facet = NULL,\n  strip_width = 15\n)\n}\n\\arguments{\n\\item{object}{compareClusterResult object}\n\n\\item{...}{additional parameters.}\n\n\\item{x}{variable for x-axis, one of 'GeneRatio' and 'Count'}\n\n\\item{color}{variable used to color enriched terms,\ne.g. 'pvalue', 'p.adjust' or 'qvalue'}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{size}{variable used to scale the sizes of categories,\none of \"geneRatio\", \"Percentage\" and \"count\"}\n\n\\item{split}{apply \\code{showCategory} to each category specified by the 'split', e.g., \"ONTOLOGY\", \"category\" and \"intersect\".  Default is NULL and do nothing}\n\n\\item{font.size}{font size}\n\n\\item{title}{figure title}\n\n\\item{orderBy}{The order of the Y-axis}\n\n\\item{label_format}{a numeric value sets wrap length, alternatively a\ncustom function to format axis labels.\nby default wraps names longer than 30 characters}\n\n\\item{by}{one of \"geneRatio\", \"Percentage\" and \"count\"}\n\n\\item{includeAll}{logical value}\n\n\\item{decreasing}{logical. Should the orderBy order be increasing or decreasing?}\n\n\\item{colorBy}{variable used to color enriched terms,\ne.g. 'pvalue', 'p.adjust' or 'qvalue'}\n\n\\item{group}{a logical value, whether to connect the\nnodes of the same group with wires.}\n\n\\item{shape}{a logical value, whether to use nodes of\ndifferent shapes to distinguish the group it belongs to}\n\n\\item{facet}{apply \\code{facet_grid} to the plot by specified variable, e.g., \"ONTOLOGY\", \"category\" and \"intersect\".}\n\n\\item{strip_width}{width of strip text (facet label).}\n}\n\\value{\nplot.\n}\n\\description{\nDot plot for enrichment result\n}\n\\examples{\n\\dontrun{\n    library(DOSE)\n    data(geneList)\n    de <- names(geneList)[1:100]\n    x <- enrichDO(de)\n    dotplot(x)\n    # use `showCategory` to select the displayed terms. It can be a number of a vector of terms.\n    dotplot(x, showCategory = 10)\n    categories <- c(\"pre-malignant neoplasm\", \"intestinal disease\",\n                   \"breast ductal carcinoma\", \"non-small cell lung carcinoma\")\n    dotplot(x, showCategory = categories)\n    # It can also graph compareClusterResult\n    data(gcSample)\n    library(clusterProfiler)\n    library(DOSE)\n    library(org.Hs.eg.db)\n    data(gcSample)\n    xx <- compareCluster(gcSample, fun=\"enrichGO\", OrgDb=\"org.Hs.eg.db\")\n    xx2 <- pairwise_termsim(xx)\n    library(ggstar)\n    dotplot(xx2)\n    dotplot(xx2, shape = TRUE)\n    dotplot(xx2, group = TRUE)\n    dotplot(xx2, x = \"GeneRatio\", group = TRUE, size = \"count\")\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/dotplot2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/dotplot.R\n\\name{dotplot2}\n\\alias{dotplot2}\n\\title{dotplot2}\n\\usage{\ndotplot2(object, x = \"FoldEnrichment\", vars = NULL, label = \"auto\", ...)\n}\n\\arguments{\n\\item{object}{a compareClusterResult object}\n\n\\item{x}{selected variable to visualize in x-axis}\n\n\\item{vars}{selected Clusters to be compared, only length of two is supported}\n\n\\item{label}{to label the Clusters in the plot, should be a named vector}\n\n\\item{...}{additional parameters passed to dotplot}\n}\n\\value{\na ggplot object\n}\n\\description{\ncompare two clusters in the compareClusterResult object\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/emapplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/emapplot.R\n\\name{emapplot}\n\\alias{emapplot}\n\\alias{emapplot,enrichResult-method}\n\\alias{emapplot,gseaResult-method}\n\\alias{emapplot,compareClusterResult-method}\n\\alias{emapplot_internal}\n\\title{emapplot}\n\\usage{\nemapplot(x, ...)\n\n\\S4method{emapplot}{enrichResult}(x, showCategory = 30, ...)\n\n\\S4method{emapplot}{gseaResult}(x, showCategory = 30, ...)\n\n\\S4method{emapplot}{compareClusterResult}(x, showCategory = 30, ...)\n\nemapplot_internal(\n  x,\n  layout = igraph::layout_with_kk,\n  showCategory = 30,\n  color = \"p.adjust\",\n  size_category = 1,\n  min_edge = 0.2,\n  color_edge = \"grey\",\n  size_edge = 0.5,\n  node_label = \"category\",\n  node_label_size = 5,\n  pie = \"equal\",\n  label_format = 30,\n  clusterFunction = stats::kmeans,\n  nWords = 4,\n  nCluster = NULL\n)\n}\n\\arguments{\n\\item{x}{Enrichment result.}\n\n\\item{...}{Additional parameters}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{layout}{igraph layout}\n\n\\item{color}{Variable used to color enriched terms, e.g. 'pvalue',\n'p.adjust' or 'qvalue'.}\n\n\\item{size_category}{relative size of the categories}\n\n\\item{min_edge}{The minimum similarity threshold for whether\ntwo nodes are connected, should be between 0 and 1, default value is 0.2.}\n\n\\item{color_edge}{color of the network edge}\n\n\\item{size_edge}{relative size of edge width}\n\n\\item{node_label}{Select which labels to display,\none of 'category', 'group', 'all' and 'none'.}\n\n\\item{node_label_size}{size of node label, default is 5.}\n\n\\item{pie}{one of 'equal' or 'Count' to set the slice ratio of the pies}\n\n\\item{label_format}{a numeric value sets wrap length, alternatively a custom function to format axis labels.}\n\n\\item{clusterFunction}{clustering method function, such as \\code{stats::kmeans} (default),\n\\code{cluster::clara}, \\code{cluster::fanny}, or \\code{cluster::pam}.}\n\n\\item{nWords}{Numeric, the number of words in the cluster tags, the default value is 4.}\n\n\\item{nCluster}{Numeric, the number of clusters,\nthe default value is square root of the number of nodes.}\n}\n\\value{\nggplot object\n}\n\\description{\nEnrichment Map for enrichment result of\nover-representation test or gene set enrichment analysis\n}\n\\details{\nThis function visualizes gene sets as a network (i.e. enrichment map).\nMutually overlapping gene sets tend to cluster together, making it\neasier for interpretation. When the similarity between terms meets\na certain threshold (default is 0.2, adjusted by parameter \\code{min_edge}),\nthere will be edges between terms. The stronger the similarity,\nthe shorter and thicker the edges. The similarity between terms is\nobtained by the function \\code{pairwise_termsim}. Details of the similarity\ncalculation can be found in its documentation: \\code{\\link[=pairwise_termsim]{pairwise_termsim()}}.\n}\n\\examples{\n\\dontrun{\n    library(DOSE)\n    data(geneList)\n    de <- names(geneList)[1:100]\n    x <- enrichDO(de)\n    x2 <- pairwise_termsim(x)\n    emapplot(x2)\n    # use `layout` to change the layout of map\n    emapplot(x2, layout = \"star\")\n    # use `showCategory` to  select the displayed terms. It can be a number of a vector of terms.\n    emapplot(x2, showCategory = 10)\n    categories <- c(\"pre-malignant neoplasm\", \"intestinal disease\",\n                   \"breast ductal carcinoma\")\n    emapplot(x2, showCategory = categories)\n\n    # It can also graph compareClusterResult\n    library(clusterProfiler)\n    library(DOSE)\n    library(org.Hs.eg.db)\n    data(gcSample)\n    xx <- compareCluster(gcSample, fun=\"enrichGO\", OrgDb=\"org.Hs.eg.db\")\n    xx2 <- pairwise_termsim(xx)\n    emapplot(xx2)\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/enrichplot-common-params.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R\n\\name{enrichplot-common-params}\n\\alias{enrichplot-common-params}\n\\title{Shared parameters for enrichment plots}\n\\arguments{\n\\item{color}{variable used to color enriched terms, e.g. \\code{'pvalue'},\n\\code{'p.adjust'}, or \\code{'qvalue'}.}\n\n\\item{showCategory}{number of categories to display, or a vector of terms.}\n\n\\item{size}{variable used to scale category size, one of \\code{\"geneRatio\"},\n\\code{\"Percentage\"}, or \\code{\"count\"}.}\n\n\\item{split}{apply \\code{showCategory} to each category specified by \\code{split},\ne.g., \\code{\"ONTOLOGY\"}, \\code{\"category\"}, or \\code{\"intersect\"}. Default is \\code{NULL}.}\n\n\\item{font.size}{font size.}\n\n\\item{title}{figure title.}\n\n\\item{label_format}{a numeric wrap width, or a custom function to format\naxis labels.}\n\n\\item{includeAll}{logical value.}\n}\n\\description{\nShared parameters for enrichment plots\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/enrichplot-package.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/enrichplot-package.R\n\\docType{package}\n\\name{enrichplot-package}\n\\alias{enrichplot}\n\\alias{enrichplot-package}\n\\title{enrichplot: Visualization of Functional Enrichment Result}\n\\description{\nThe 'enrichplot' package provides visualization methods for interpreting functional enrichment results from ORA or GSEA analyses. It is designed to work with the 'clusterProfiler' ecosystem and builds on 'ggplot2' for flexible and extensible graphics.\n}\n\\seealso{\nUseful links:\n\\itemize{\n  \\item \\url{https://yulab-smu.top/contribution-knowledge-mining/}\n  \\item Report bugs at \\url{https://github.com/GuangchuangYu/enrichplot/issues}\n}\n\n}\n\\author{\n\\strong{Maintainer}: Guangchuang Yu \\email{guangchuangyu@gmail.com} (\\href{https://orcid.org/0000-0002-6485-8781}{ORCID})\n\nOther contributors:\n\\itemize{\n  \\item Chun-Hui Gao \\email{gaospecial@gmail.com} (\\href{https://orcid.org/0000-0002-1445-7939}{ORCID}) [contributor]\n}\n\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/enrichplot-term-params.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R\n\\name{enrichplot-term-params}\n\\alias{enrichplot-term-params}\n\\title{Shared term-plot parameters}\n\\arguments{\n\\item{showCategory}{number of categories to display, or a vector of terms.}\n\n\\item{color}{variable used to color enriched terms, e.g. \\code{'pvalue'},\n\\code{'p.adjust'}, or \\code{'qvalue'}.}\n\n\\item{label_format}{a numeric wrap width, or a custom function to format\naxis labels.}\n}\n\\description{\nShared term-plot parameters\n}\n\\keyword{internal}\n"
  },
  {
    "path": "man/enrichplot_point_shape.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/color_utils.R\n\\docType{data}\n\\name{enrichplot_point_shape}\n\\alias{enrichplot_point_shape}\n\\title{Predefined color palettes}\n\\format{\nAn object of class \\code{numeric} of length 1.\n}\n\\usage{\nenrichplot_point_shape\n}\n\\description{\nPredefined color palettes\n}\n\\keyword{datasets}\n"
  },
  {
    "path": "man/fortify.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/method-fortify.R\n\\name{fortify.compareClusterResult}\n\\alias{fortify.compareClusterResult}\n\\alias{fortify.enrichResult}\n\\title{fortify}\n\\usage{\n\\method{fortify}{compareClusterResult}(\n  model,\n  data,\n  showCategory = 5,\n  by = \"geneRatio\",\n  split = NULL,\n  includeAll = TRUE,\n  ...\n)\n\n\\method{fortify}{enrichResult}(\n  model,\n  data,\n  showCategory = 5,\n  by = \"Count\",\n  order = FALSE,\n  drop = FALSE,\n  split = NULL,\n  ...\n)\n}\n\\arguments{\n\\item{model}{'enrichResult' or 'compareClusterResult' object}\n\n\\item{data}{not use here}\n\n\\item{showCategory}{Category numbers to show}\n\n\\item{by}{one of Count and GeneRatio}\n\n\\item{split}{separate result by 'split' variable}\n\n\\item{includeAll}{logical}\n\n\\item{...}{additional parameter}\n\n\\item{order}{logical}\n\n\\item{drop}{logical}\n}\n\\value{\ndata.frame\n\ndata.frame\n}\n\\description{\nconvert compareClusterResult to a data.frame that ready for plot\n\nconvert enrichResult object for ggplot2\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/geom_gsea_gene.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gseaplot.R\n\\name{geom_gsea_gene}\n\\alias{geom_gsea_gene}\n\\title{geom_gsea_gene}\n\\usage{\ngeom_gsea_gene(\n  genes,\n  mapping = NULL,\n  geom = ggplot2::geom_text,\n  ...,\n  geneSet = NULL\n)\n}\n\\arguments{\n\\item{genes}{selected genes to be labeled}\n\n\\item{mapping}{aesthetic mapping, default is NULL}\n\n\\item{geom}{geometric layer to plot the gene labels, default is geom_text}\n\n\\item{...}{additional parameters passed to the 'geom'}\n\n\\item{geneSet}{choose which gene set(s) to be label if the plot contains multiple gene sets}\n}\n\\value{\nggplot object\n}\n\\description{\nlabel genes in running score plot\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/get_enrichplot_color.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/color_utils.R\n\\name{get_enrichplot_color}\n\\alias{get_enrichplot_color}\n\\title{Color utility functions for enrichplot package}\n\\usage{\nget_enrichplot_color(n = 2)\n}\n\\arguments{\n\\item{n}{number of colors (2 or 3)}\n}\n\\value{\ncolor vector\n}\n\\description{\nThis file contains all color-related helper functions\nGet default enrichplot colors\n}\n"
  },
  {
    "path": "man/ggtable.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/ggtable.R\n\\name{ggtable}\n\\alias{ggtable}\n\\title{ggtable}\n\\usage{\nggtable(d, p = NULL)\n}\n\\arguments{\n\\item{d}{data frame}\n\n\\item{p}{ggplot object to extract color to color rownames(d), optional}\n}\n\\value{\nggplot object\n}\n\\description{\nplot table\n}\n\\author{\nguangchuang yu\n}\n"
  },
  {
    "path": "man/goplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/goplot.R\n\\name{goplot}\n\\alias{goplot}\n\\alias{goplot,enrichResult-method}\n\\alias{goplot,gseaResult-method}\n\\title{goplot}\n\\usage{\ngoplot(\n  x,\n  showCategory = 10,\n  color = \"p.adjust\",\n  layout = \"sugiyama\",\n  geom = \"text\",\n  ...\n)\n\n\\S4method{goplot}{enrichResult}(\n  x,\n  showCategory = 10,\n  color = \"p.adjust\",\n  layout = igraph::layout_with_sugiyama,\n  geom = \"text\",\n  ...\n)\n\n\\S4method{goplot}{gseaResult}(\n  x,\n  showCategory = 10,\n  color = \"p.adjust\",\n  layout = igraph::layout_with_sugiyama,\n  geom = \"text\",\n  ...\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{showCategory}{number of categories to display, or a vector of terms.}\n\n\\item{color}{variable used to color enriched terms, e.g. \\code{'pvalue'},\n\\code{'p.adjust'}, or \\code{'qvalue'}.}\n\n\\item{layout}{layout of the map}\n\n\\item{geom}{label geom, one of 'label' or 'text'}\n\n\\item{...}{additional parameters.}\n}\n\\value{\nggplot object\n}\n\\description{\nPlot induced GO DAG of significant terms\n}\n\\examples{\n\\dontrun{\n\tlibrary(clusterProfiler)\n  data(geneList, package = \"DOSE\")\n\tde <- names(geneList)[1:100]\n\tyy <- enrichGO(de, 'org.Hs.eg.db', ont=\"BP\", pvalueCutoff=0.01)\n    goplot(yy)\n    goplot(yy, showCategory = 5)\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/gsInfo.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gseaplot.R\n\\name{gsInfo}\n\\alias{gsInfo}\n\\title{gsInfo}\n\\usage{\ngsInfo(object, geneSetID)\n}\n\\arguments{\n\\item{object}{gseaResult object}\n\n\\item{geneSetID}{gene set ID}\n}\n\\value{\ndata.frame\n}\n\\description{\nextract gsea result of selected geneSet\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/gseadist.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/densityplot.R\n\\name{gseadist}\n\\alias{gseadist}\n\\title{gseadist}\n\\usage{\ngseadist(x, IDs, type = \"density\")\n}\n\\arguments{\n\\item{x}{GSEA result}\n\n\\item{IDs}{gene set IDs}\n\n\\item{type}{one of 'density' or 'boxplot'}\n}\n\\value{\ndistribution plot\n}\n\\description{\nplot logFC distribution of selected gene sets\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/gseaplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/gseaplot.R\n\\name{gseaplot}\n\\alias{gseaplot}\n\\alias{gseaplot,gseaResult-method}\n\\alias{gseaplot.gseaResult}\n\\title{gseaplot}\n\\usage{\ngseaplot(x, geneSetID, by = \"all\", title = \"\", ...)\n\n\\S4method{gseaplot}{gseaResult}(\n  x,\n  geneSetID,\n  by = \"all\",\n  title = \"\",\n  color = \"black\",\n  color.line = \"green\",\n  color.vline = \"#FA5860\",\n  ...\n)\n\ngseaplot.gseaResult(\n  x,\n  geneSetID,\n  by = \"all\",\n  title = \"\",\n  color = \"black\",\n  color.line = \"green\",\n  color.vline = \"#FA5860\",\n  ...\n)\n}\n\\arguments{\n\\item{x}{gseaResult object}\n\n\\item{geneSetID}{geneSet ID}\n\n\\item{by}{one of \"runningScore\" or \"position\"}\n\n\\item{title}{plot title}\n\n\\item{...}{additional parameters}\n\n\\item{color}{color of line segments}\n\n\\item{color.line}{color of running enrichment score line}\n\n\\item{color.vline}{color of vertical line indicating the\nmaximum/minimal running enrichment score}\n}\n\\value{\nggplot2 object\n\nggplot2 object\n}\n\\description{\nVisualize GSEA analysis results\n}\n\\details{\nPlotting function for gseaResult\n}\n\\examples{\n\\donttest{\nlibrary(DOSE)\ndata(geneList)\nx <- gseDO(geneList)\ngseaplot(x, geneSetID=1)\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/gseaplot2.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gseaplot.R\n\\name{gseaplot2}\n\\alias{gseaplot2}\n\\title{gseaplot2}\n\\usage{\ngseaplot2(\n  x,\n  geneSetID,\n  title = \"\",\n  color = \"green\",\n  base_size = 11,\n  rel_heights = c(1.5, 0.5, 1),\n  subplots = 1:3,\n  pvalue_table = FALSE,\n  pvalue_table_columns = c(\"pvalue\", \"p.adjust\"),\n  pvalue_table_rownames = \"Description\",\n  ES_geom = \"line\"\n)\n}\n\\arguments{\n\\item{x}{gseaResult object}\n\n\\item{geneSetID}{gene set ID}\n\n\\item{title}{plot title}\n\n\\item{color}{color of running enrichment score line}\n\n\\item{base_size}{base font size}\n\n\\item{rel_heights}{relative heights of subplots}\n\n\\item{subplots}{which subplots to be displayed}\n\n\\item{pvalue_table}{whether add pvalue table}\n\n\\item{pvalue_table_columns}{selected columns to be plotted in the \\code{pvalue_table}}\n\n\\item{pvalue_table_rownames}{selected column as the rownames of the \\code{pvalue_table}. If set to NULL, no rownames will be displayed.}\n\n\\item{ES_geom}{geom for plotting running enrichment score,\none of 'line' or 'dot'}\n}\n\\value{\nplot\n}\n\\description{\nGSEA plot that mimic the plot generated by broad institute's GSEA software\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/gsearank.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gseaplot.R\n\\name{gsearank}\n\\alias{gsearank}\n\\title{gsearank}\n\\usage{\ngsearank(x, geneSetID, title = \"\", output = \"plot\")\n}\n\\arguments{\n\\item{x}{gseaResult object}\n\n\\item{geneSetID}{gene set ID}\n\n\\item{title}{plot title}\n\n\\item{output}{one of 'plot' or 'table' (for exporting data)}\n}\n\\value{\nggplot object\n}\n\\description{\nplot ranked list of genes with running enrichment score as bar height\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/heatplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/heatplot.R\n\\name{heatplot}\n\\alias{heatplot}\n\\alias{heatplot,enrichResult-method}\n\\alias{heatplot,gseaResult-method}\n\\alias{heatplot.enrichResult}\n\\title{heatplot}\n\\usage{\nheatplot(x, showCategory = 30, ...)\n\n\\S4method{heatplot}{enrichResult}(x, showCategory = 30, ...)\n\n\\S4method{heatplot}{gseaResult}(x, showCategory = 30, ...)\n\nheatplot.enrichResult(\n  x,\n  showCategory = 30,\n  showTop = NULL,\n  symbol = \"rect\",\n  foldChange = NULL,\n  pvalue = NULL,\n  label_format = 30\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{showCategory}{number of enriched terms to display}\n\n\\item{...}{Additional parameters}\n\n\\item{showTop}{number of top genes ranked by \\code{abs(foldChange) * frequency}\nto be shown in the heatmap, default NULL means all genes are shown}\n\n\\item{symbol}{symbol of the nodes, one of \"rect\" (the default) or \"dot\"}\n\n\\item{foldChange}{fold change.}\n\n\\item{pvalue}{pvalue of genes}\n\n\\item{label_format}{a numeric value sets wrap length, alternatively a\ncustom function to format axis labels.\nby default wraps names longer than 30 characters}\n}\n\\value{\nggplot object\n}\n\\description{\nHeatmap-like plot for functional classification\n}\n\\examples{\nlibrary(DOSE)\ndata(geneList)\nde <- names(geneList)[1:100]\nx <- enrichDO(de)\nheatplot(x)\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/hplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/gseaplot.R\n\\name{hplot}\n\\alias{hplot}\n\\title{hplot}\n\\usage{\nhplot(x, geneSetID)\n}\n\\arguments{\n\\item{x}{gseaResult object}\n\n\\item{geneSetID}{gene set ID}\n}\n\\value{\nhorizontal plot\n}\n\\description{\nHorizontal plot for GSEA result\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/manhattanplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/manhattanplot.R\n\\name{manhattanplot}\n\\alias{manhattanplot}\n\\alias{manhattanplot,enrichResult-method}\n\\alias{manhattanplot,gseaResult-method}\n\\alias{manhattanplot,compareClusterResult-method}\n\\alias{manhattanplot,compareClusterResult,ANY-method}\n\\alias{manhattanplot,enrichResultList-method}\n\\alias{manhattanplot,enrichResultList,ANY-method}\n\\alias{manhattanplot,gseaResultList-method}\n\\alias{manhattanplot,gseaResultList,ANY-method}\n\\alias{manhattanplot,list-method}\n\\alias{manhattanplot,list,ANY-method}\n\\title{manhattanplot}\n\\usage{\nmanhattanplot(x, ...)\n\n\\S4method{manhattanplot}{enrichResult}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  size = \"Count\",\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{manhattanplot}{gseaResult}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  size = \"Count\",\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{manhattanplot}{compareClusterResult}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  size = \"Count\",\n  includeAll = TRUE,\n  label_format = 30,\n  ...\n)\n\n\\S4method{manhattanplot}{enrichResultList}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  size = \"Count\",\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{manhattanplot}{gseaResultList}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  size = \"Count\",\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n\n\\S4method{manhattanplot}{list}(\n  x,\n  color = \"p.adjust\",\n  showCategory = 5,\n  size = \"Count\",\n  split = NULL,\n  font.size = 12,\n  title = \"\",\n  label_format = 30,\n  ...\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{...}{additional parameters.}\n\n\\item{color}{variable used to color enriched terms, e.g. \\code{'pvalue'},\n\\code{'p.adjust'}, or \\code{'qvalue'}.}\n\n\\item{showCategory}{number of categories to display, or a vector of terms.}\n\n\\item{size}{variable used to scale category size, one of \\code{\"geneRatio\"},\n\\code{\"Percentage\"}, or \\code{\"count\"}.}\n\n\\item{split}{apply \\code{showCategory} to each category specified by \\code{split},\ne.g., \\code{\"ONTOLOGY\"}, \\code{\"category\"}, or \\code{\"intersect\"}. Default is \\code{NULL}.}\n\n\\item{font.size}{font size.}\n\n\\item{title}{figure title.}\n\n\\item{label_format}{a numeric wrap width, or a custom function to format\naxis labels.}\n\n\\item{includeAll}{logical value.}\n}\n\\value{\nggplot object\n}\n\\description{\nManhattan plot for enrichment result\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/pairwise_termsim.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/pairwise_termsim.R\n\\name{pairwise_termsim}\n\\alias{pairwise_termsim}\n\\alias{pairwise_termsim,enrichResult-method}\n\\alias{pairwise_termsim,gseaResult-method}\n\\alias{pairwise_termsim,compareClusterResult-method}\n\\alias{pairwise_termsim.enrichResult}\n\\alias{pairwise_termsim.compareClusterResult}\n\\title{pairwise_termsim}\n\\usage{\npairwise_termsim(x, method = \"JC\", semData = NULL, showCategory = NULL)\n\n\\S4method{pairwise_termsim}{enrichResult}(x, method = \"JC\", semData = NULL, showCategory = NULL)\n\n\\S4method{pairwise_termsim}{gseaResult}(x, method = \"JC\", semData = NULL, showCategory = NULL)\n\n\\S4method{pairwise_termsim}{compareClusterResult}(x, method = \"JC\", semData = NULL, showCategory = NULL)\n\npairwise_termsim.enrichResult(\n  x,\n  method = \"JC\",\n  semData = NULL,\n  showCategory = NULL\n)\n\npairwise_termsim.compareClusterResult(\n  x,\n  method = \"JC\",\n  semData = NULL,\n  showCategory = NULL\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{method}{method of calculating the similarity between nodes,\none of \"Resnik\", \"Lin\", \"Rel\", \"Jiang\", \"Wang\", and\n\"JC\" (Jaccard similarity coefficient) methods.}\n\n\\item{semData}{\\code{GOSemSimDATA} object, can be obtained through\n\\code{GOSemSim::godata}.}\n\n\\item{showCategory}{number of enriched terms to be calculated. The default value is the number of enriched terms, or 200 if the number of enriched terms exceeds 200.}\n}\n\\description{\nGet the similarity matrix\n}\n\\details{\nThis function adds a similarity matrix to the termsim slot of the enrichment result.\nUsers can use the \\code{method} parameter to select the method of calculating the similarity.\nThe Jaccard correlation coefficient (JC) is used by default, and it applies to all situations.\nWhen users want to calculate the correlation between GO terms or DO terms, they can also choose\n\"Resnik\", \"Lin\", \"Rel\" or \"Jiang\" (they are semantic similarity calculation methods from the 'GOSemSim' package),\nand at this time, the user needs to provide the \\code{semData} parameter, which can be obtained through\n\\code{\\link[GOSemSim:godata]{GOSemSim::godata()}}.\n}\n\\examples{\n\\dontrun{\n    library(clusterProfiler)\n    library(org.Hs.eg.db)\n    library(enrichplot)\n    library(GOSemSim)\n    library(DOSE)\n    data(geneList)\n    gene <- names(geneList)[abs(geneList) > 2]\n    ego <- enrichGO(gene  = gene,\n        universe      = names(geneList),\n        OrgDb         = org.Hs.eg.db,\n        ont           = \"BP\",\n        pAdjustMethod = \"BH\",\n        pvalueCutoff  = 0.01,\n        qvalueCutoff  = 0.05,\n        readable      = TRUE)\n    d <- godata('org.Hs.eg.db', ont=\"BP\")\n    ego2 <- pairwise_termsim(ego, method=\"Wang\", semData = d)\n    emapplot(ego2)\n    emapplot_cluster(ego2)\n   }\n}\n"
  },
  {
    "path": "man/plotting.clusterProfile.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/plot_utils.R\n\\name{plotting.clusterProfile}\n\\alias{plotting.clusterProfile}\n\\title{Internal plot function for plotting compareClusterResult}\n\\usage{\nplotting.clusterProfile(\n  clProf.reshape.df,\n  x = ~Cluster,\n  type = \"dot\",\n  colorBy = \"p.adjust\",\n  by = \"geneRatio\",\n  title = \"\",\n  font.size = 12\n)\n}\n\\arguments{\n\\item{clProf.reshape.df}{data frame of compareCluster result}\n\n\\item{x}{x variable}\n\n\\item{type}{one of dot and bar}\n\n\\item{colorBy}{one of pvalue or p.adjust}\n\n\\item{by}{one of percentage and count}\n\n\\item{title}{graph title}\n\n\\item{font.size}{graph font size}\n}\n\\value{\nggplot object\n}\n\\description{\nInternal plot function for plotting compareClusterResult\n}\n\\author{\nGuangchuang Yu \\url{https://yulab-smu.top}\n}\n"
  },
  {
    "path": "man/pmcplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/pmcplot.R\n\\name{pmcplot}\n\\alias{pmcplot}\n\\title{pmcplot}\n\\usage{\npmcplot(query, period, proportion = TRUE)\n}\n\\arguments{\n\\item{query}{query terms}\n\n\\item{period}{period of query in the unit of year}\n\n\\item{proportion}{If TRUE, use query_hits/all_hits, otherwise use query_hits.}\n}\n\\value{\nggplot object\n}\n\\description{\nPubMed Central Trend plot\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/reexports.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/reexport.R\n\\docType{import}\n\\name{reexports}\n\\alias{reexports}\n\\alias{ggtitle}\n\\alias{facet_grid}\n\\alias{plot_list}\n\\alias{cnetplot}\n\\alias{theme_dose}\n\\alias{geom_cnet_label}\n\\alias{gseaScores}\n\\alias{geneID}\n\\alias{geneInCategory}\n\\title{Objects exported from other packages}\n\\keyword{internal}\n\\description{\nThese objects are imported from other packages. Follow the links\nbelow to see their documentation.\n\n\\describe{\n  \\item{aplot}{\\code{\\link[aplot]{plot_list}}}\n\n  \\item{DOSE}{\\code{\\link[DOSE]{theme_dose}}}\n\n  \\item{enrichit}{\\code{\\link[enrichit]{geneID}}, \\code{\\link[enrichit]{geneInCategory}}, \\code{\\link[enrichit]{gseaScores}}}\n\n  \\item{ggplot2}{\\code{\\link[ggplot2]{facet_grid}}, \\code{\\link[ggplot2:labs]{ggtitle}}}\n\n  \\item{ggtangle}{\\code{\\link[ggtangle]{cnetplot}}, \\code{\\link[ggtangle]{geom_cnet_label}}}\n}}\n\n"
  },
  {
    "path": "man/ridgeplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/ridgeplot.R\n\\name{ridgeplot}\n\\alias{ridgeplot}\n\\alias{ridgeplot,gseaResult-method}\n\\alias{ridgeplot.gseaResult}\n\\title{ridgeplot}\n\\usage{\nridgeplot(\n  x,\n  showCategory = 30,\n  fill = \"p.adjust\",\n  core_enrichment = TRUE,\n  label_format = 30,\n  ...\n)\n\n\\S4method{ridgeplot}{gseaResult}(\n  x,\n  showCategory = 30,\n  fill = \"p.adjust\",\n  core_enrichment = TRUE,\n  label_format = 30,\n  ...\n)\n\nridgeplot.gseaResult(\n  x,\n  showCategory = 30,\n  fill = \"p.adjust\",\n  core_enrichment = TRUE,\n  label_format = 30,\n  orderBy = \"NES\",\n  decreasing = FALSE,\n  stat = \"density_ridges\"\n)\n}\n\\arguments{\n\\item{x}{gseaResult object}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{fill}{one of \"pvalue\", \"p.adjust\", \"qvalue\"}\n\n\\item{core_enrichment}{whether to use only core_enriched genes}\n\n\\item{label_format}{a numeric value setting the wrap length, alternatively a\ncustom function to format axis labels.}\n\n\\item{...}{additional parameters.}\n\n\\item{orderBy}{The order of the Y-axis}\n\n\\item{decreasing}{logical. Should the orderBy order be increasing or decreasing?}\n\n\\item{stat}{statistic passed to \\code{ggridges::geom_density_ridges()}.}\n}\n\\value{\nggplot object\n}\n\\description{\nRidgeline plot for GSEA result\n}\n\\examples{\n\\donttest{\nlibrary(DOSE)\ndata(geneList)\nx <- gseDO(geneList)\nridgeplot(x)\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/set_enrichplot_color.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/color_utils.R\n\\name{set_enrichplot_color}\n\\alias{set_enrichplot_color}\n\\title{Helper function to set color scale for enrichplot}\n\\usage{\nset_enrichplot_color(\n  colors = get_enrichplot_color(2),\n  type = \"color\",\n  name = NULL,\n  .fun = NULL,\n  reverse = TRUE,\n  transform = \"identity\",\n  ...\n)\n}\n\\arguments{\n\\item{colors}{user provided color vector}\n\n\\item{type}{one of 'color', 'colour' or 'fill'}\n\n\\item{name}{name of the color legend}\n\n\\item{.fun}{force to use user provided color scale function}\n\n\\item{reverse}{whether reverse the color scheme}\n\n\\item{transform}{transform the color scale}\n\n\\item{...}{additional parameters}\n}\n\\value{\na color scale\n}\n\\description{\nHelper function to set color scale for enrichplot\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/ssplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/ssplot.R\n\\name{ssplot}\n\\alias{ssplot}\n\\alias{ssplot,enrichResult-method}\n\\alias{ssplot,gseaResult-method}\n\\alias{ssplot,compareClusterResult-method}\n\\alias{ssplot.enrichResult}\n\\alias{ssplot.compareClusterResult}\n\\title{ssplot}\n\\usage{\nssplot(x, ...)\n\n\\S4method{ssplot}{enrichResult}(x, showCategory = 30, ...)\n\n\\S4method{ssplot}{gseaResult}(x, showCategory = 30, ...)\n\n\\S4method{ssplot}{compareClusterResult}(x, showCategory = 30, ...)\n\nssplot.enrichResult(\n  x,\n  showCategory = 30,\n  drfun = NULL,\n  dr.params = list(),\n  node_label = \"group\",\n  ...\n)\n\nssplot.compareClusterResult(\n  x,\n  showCategory = 30,\n  pie = \"equal\",\n  drfun = NULL,\n  dr.params = list(),\n  node_label = \"group\",\n  ...\n)\n}\n\\arguments{\n\\item{x}{Enrichment result.}\n\n\\item{...}{additional parameters\n\nAdditional plotting parameters are inherited from \\code{\\link[=emapplot]{emapplot()}}.}\n\n\\item{showCategory}{number of categories to display or a vector of terms.}\n\n\\item{drfun}{The function used for dimension reduction,\ne.g. \\code{stats::cmdscale} (the default), \\code{vegan::metaMDS}, or \\code{ape::pcoa}.}\n\n\\item{dr.params}{list, the parameters of \\code{tidydr::dr}.}\n\n\\item{node_label}{Select which labels to display,\none of 'category', 'group', 'all' and 'none'.}\n\n\\item{pie}{one of 'equal' or 'Count' to set the slice ratio of the pies}\n}\n\\value{\nggplot object\n}\n\\description{\nSimilarity Space Plot for enrichment analysis\n}\n\\details{\nCreates 2D visualization of enrichment results using dimension reduction\ntechniques to show relationships between terms based on similarity.\n}\n\\examples{\n\\dontrun{\n    library(clusterProfiler)\n    library(org.Hs.eg.db)\n    library(enrichplot)\n    library(GOSemSim)\n    library(DOSE)\n    data(geneList)\n    gene <- names(geneList)[abs(geneList) > 2]\n    ego <- enrichGO(gene  = gene,\n        universe      = names(geneList),\n        OrgDb         = org.Hs.eg.db,\n        ont           = \"BP\",\n        pAdjustMethod = \"BH\",\n        pvalueCutoff  = 0.01,\n        qvalueCutoff  = 0.05,\n        readable      = TRUE)\n    d <- godata('org.Hs.eg.db', ont=\"BP\")\n    ego2 <- pairwise_termsim(ego, method = \"Wang\", semData = d)\n    ssplot(ego2)\n}\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/treeplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/treeplot.R\n\\name{treeplot}\n\\alias{treeplot}\n\\alias{treeplot,enrichResult-method}\n\\alias{treeplot,gseaResult-method}\n\\alias{treeplot,compareClusterResult-method}\n\\alias{treeplot_internal}\n\\title{treeplot}\n\\usage{\ntreeplot(x, ...)\n\n\\S4method{treeplot}{enrichResult}(x, ...)\n\n\\S4method{treeplot}{gseaResult}(x, ...)\n\n\\S4method{treeplot}{compareClusterResult}(x, ...)\n\ntreeplot_internal(\n  x,\n  showCategory = 30,\n  color = \"p.adjust\",\n  size_var = c(\"Count\", \"setSize\"),\n  nCluster = 5,\n  cluster_method = \"ward.D\",\n  label_format = 30,\n  fontsize_tiplab = 4,\n  fontsize_cladelab = 4,\n  group_color = NULL,\n  extend = 0.3,\n  hilight = TRUE,\n  align = \"both\",\n  hexpand = 0.1,\n  tiplab_offset = 0.2,\n  cladelab_offset = 1\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{...}{additional parameters}\n\n\\item{showCategory}{number of enriched terms to display}\n\n\\item{color}{variable to color nodes, e.g. 'p.adjust', 'pvalue', or 'qvalue'}\n\n\\item{size_var}{variable for node size, e.g. 'Count' (for enrichResult) or 'setSize' (for gseaResult)}\n\n\\item{nCluster}{number of clusters for tree cutting}\n\n\\item{cluster_method}{hierarchical clustering method}\n\n\\item{label_format}{wrap length for labels or custom formatting function}\n\n\\item{fontsize_tiplab}{font size for tip labels}\n\n\\item{fontsize_cladelab}{font size for clade labels}\n\n\\item{group_color}{vector of colors for groups}\n\n\\item{extend}{extend length for clade labels}\n\n\\item{hilight}{whether to highlight clades}\n\n\\item{align}{alignment for highlight rectangles}\n\n\\item{hexpand}{expand x limits by amount of xrange * hexpand}\n\n\\item{tiplab_offset}{offset for tip labels}\n\n\\item{cladelab_offset}{offset for clade labels}\n}\n\\value{\nggplot object\n\nggplot2 object representing the tree plot\n}\n\\description{\nFunctional grouping tree diagram for enrichment result of\nover-representation test or gene set enrichment analysis.\n\nCreates hierarchical tree visualization of enriched terms based on similarity\n}\n\\details{\nThis function visualizes gene sets as a tree.\nGene sets with high similarity tend to cluster together, making it easier\nfor interpretation.\n}\n\\examples{\n\\dontrun{\n    library(clusterProfiler)\n    library(org.Hs.eg.db)\n    library(enrichplot)\n    library(GOSemSim)\n    library(ggplot2)\n    library(DOSE)\n    data(geneList)\n    gene <- names(geneList)[abs(geneList) > 2]\n    ego <- enrichGO(gene  = gene,\n        universe      = names(geneList),\n        OrgDb         = org.Hs.eg.db,\n        ont           = \"BP\",\n        pAdjustMethod = \"BH\",\n        pvalueCutoff  = 0.01,\n        qvalueCutoff  = 0.05,\n        readable      = TRUE)\n    d <- godata('org.Hs.eg.db', ont=\"BP\")\n    ego2 <- pairwise_termsim(ego, method = \"Wang\", semData = d)\n    treeplot(ego2, showCategory = 30)\n    # use `hilight = FALSE` to remove ggtree::geom_hilight() layer.\n    treeplot(ego2, showCategory = 30, hilight = FALSE)\n    # use `offset` parameter to adjust the distance of bar and tree.\n    treeplot(ego2, showCategory = 30, hilight = FALSE, offset = rel(1.5))\n    # use `offset_tiplab` parameter to adjust the distance of nodes and branches.\n    treeplot(ego2, showCategory = 30, hilight = FALSE, offset_tiplab = rel(1.5))\n    keep <- rownames(ego2@termsim)[c(1:10, 16:20)]\n    keep\n    treeplot(ego2, showCategory = keep)\n    treeplot(ego2, showCategory = 20,\n        group_color = c(\"#999999\", \"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\"))\n    # It can also graph compareClusterResult\n    data(gcSample)\n    xx <- compareCluster(gcSample, fun=\"enrichKEGG\",\n                         organism=\"hsa\", pvalueCutoff=0.05)\n    xx <- pairwise_termsim(xx)\n    treeplot(xx)\n\n    # use `geneClusterPanel` to change the gene cluster panel.\n    treeplot(xx, geneClusterPanel = \"dotplot\")\n\n    treeplot(xx, geneClusterPanel = \"pie\")\n   }\n}\n"
  },
  {
    "path": "man/upsetplot-methods.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/upsetplot.R\n\\docType{methods}\n\\name{upsetplot}\n\\alias{upsetplot}\n\\alias{upsetplot,enrichResult-method}\n\\alias{upsetplot,enrichResult,ANY-method}\n\\alias{upsetplot,gseaResult-method}\n\\alias{upsetplot,gseaResult}\n\\title{upsetplot method}\n\\usage{\nupsetplot(x, ...)\n\n\\S4method{upsetplot}{enrichResult}(x, n = 10, ...)\n\n\\S4method{upsetplot}{gseaResult}(x, n = 10, ...)\n}\n\\arguments{\n\\item{x}{object}\n\n\\item{...}{additional parameters}\n\n\\item{n}{number of categories to be plotted}\n}\n\\value{\nplot\n}\n\\description{\nupsetplot method generics\n\nUpsetplot\n}\n\\examples{\nlibrary(DOSE)\ndata(geneList)\nde <- names(geneList)[1:100]\nx <- enrichDO(de)\nupsetplot(x, 8)\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "man/volplot.Rd",
    "content": "% Generated by roxygen2: do not edit by hand\n% Please edit documentation in R/AllGenerics.R, R/volplot.R\n\\name{volplot}\n\\alias{volplot}\n\\alias{volplot,enrichResult-method}\n\\alias{volplot.enrichResult}\n\\title{volplot}\n\\usage{\nvolplot(\n  x,\n  color = \"zScore\",\n  xintercept = 1,\n  yintercept = 2,\n  showCategory = 5,\n  label_format = 30,\n  ...\n)\n\n\\S4method{volplot}{enrichResult}(\n  x,\n  color = \"zScore\",\n  xintercept = 1,\n  yintercept = 2,\n  showCategory = 5,\n  label_format = 30,\n  ...\n)\n\nvolplot.enrichResult(\n  x,\n  color = \"zScore\",\n  xintercept = 1,\n  yintercept = 2,\n  showCategory = 5,\n  label_format = 30,\n  font.size = 12,\n  size = 5\n)\n}\n\\arguments{\n\\item{x}{enrichment result.}\n\n\\item{color}{selected variable to color the dots}\n\n\\item{xintercept}{value to set x-intercept}\n\n\\item{yintercept}{value to set y-intercept}\n\n\\item{showCategory}{number of most significant enriched terms or selected terms to\ndisplay determined by the variable selected to color the dots}\n\n\\item{label_format}{a numeric value setting the wrap length, alternatively a\ncustom function to format axis labels.}\n\n\\item{...}{Additional parameters}\n\n\\item{font.size}{font size for \\code{theme_dose()}}\n\n\\item{size}{font size to label selected categories specified by showCategory}\n}\n\\value{\nggplot object\n}\n\\description{\nVolcano plot for enrichment result\n}\n\\examples{\nlibrary(DOSE)\ndata(geneList)\nde <- names(geneList)[1:100]\nx <- enrichDO(de)\nvolplot(x)\n}\n\\author{\nGuangchuang Yu\n}\n"
  },
  {
    "path": "vignettes/enrichplot.qmd",
    "content": "---\ntitle: \"Visualization of Functional Enrichment Result\"\nformat: \n    html:\n        theme: none\n        embed-resources: true\n        fontsize: 1.1em\n        linestretch: 1.7\nauthor: \"Guangchuang Yu\\\\\n\n        School of Basic Medical Sciences, Southern Medical University\"\ndate: \"`r Sys.Date()`\"\nvignette: >\n  %\\VignetteIndexEntry{enrichplot}\n  %\\VignetteEngine{quarto::html}\n  %\\VignetteEncoding{UTF-8}\n---\n\nPlease go to <https://yulab-smu.github.io/clusterProfiler-book/> for the full vignette."
  }
]