Giter VIP home page Giter VIP logo

ggnewscale's Introduction

ggnewscale

R build status Codecov test coverage DOI CRAN status

ggnewscale tries to make it painless to use multiple scales in ggplot2. Although originally intended to use with colour and fill, it should work with any aes, such as shape, linetype and the rest.

ggnewscale: spend 400% more time tweaking your ggplot!

For another way of defining multiple scales, you can also try relayer.

How to install

You can install ggnewscale from CRAN with:

install.packages("ggnewscale")

Or the development version with:

# install.packages("devtools")
devtools::install_github("eliocamp/ggnewscale")

How to cite

If you use ggnewscale in a publication, I’ll be grateful if you cited it. To get the suggested citation for this (and any other R package) you can use:

citation("ggnewscale")
#> To cite ggnewscale in publications use:
#> 
#>   Campitelli E (????). _ggnewscale: Multiple Fill and Colour Scales in
#>   'ggplot2'_. doi:10.5281/zenodo.2543762
#>   <https://doi.org/10.5281/zenodo.2543762>, R package version 0.4.10.
#> 
#> A BibTeX entry for LaTeX users is
#> 
#>   @Manual{R-ggnewscale,
#>     title = {ggnewscale: Multiple Fill and Colour Scales in 'ggplot2'},
#>     author = {Elio Campitelli},
#>     note = {R package version 0.4.10},
#>     doi = {10.5281/zenodo.2543762},
#>   }

If you use knitr, you can automate this with

knitr::write_bib(c("ggnewscale"), "packages.bib")

And then add citations with @R-ggnewscale.

Click to see a list of some publications that have cited ggnewscale. Thanks!

[1] E. Akhil Prakash, T. Hromádková, T. Jabir, et al. “Dissemination of Multidrug Resistant Bacteria to the Polar Environment - Role of the Longest Migratory Bird Arctic Tern (Sterna Paradisaea)”. In: Science of The Total Environment (Dec. 31, 2021), p. 152727. ISSN: 0048-9697. DOI: 10.1016/j.scitotenv.2021.152727. https://www.sciencedirect.com/science/article/pii/S0048969721078062 (visited on 01/03/2022).

[2] R. AminiTabrizi, R. M. Wilson, J. D. Fudyma, et al. “Controls on Soil Organic Matter Degradation and Subsequent Greenhouse Gas Emissions Across a Permafrost Thaw Gradient in Northern Sweden”. In: Frontiers in Earth Science 8 (2020). ISSN: 2296-6463. DOI: 10.3389/feart.2020.557961. https://www.frontiersin.org/articles/10.3389/feart.2020.557961/full (visited on 03/03/2021).

[3] D. Baker, J. Lauer, A. Ortega, et al. “Effects of Phycosphere Bacteria on Their Algal Host Are Host Species-Specific and Not Phylogenetically Conserved”. In: Microorganisms 11.1 (1 Jan. 2023), p. 62. ISSN: 2076-2607. DOI: 10.3390/microorganisms11010062. https://www.mdpi.com/2076-2607/11/1/62 (visited on 12/28/2022).

[4] L. Baumgarten, B. Pieper, B. Song, et al. “Pan-European Study of Genotypes and Phenotypes in the Arabidopsis Relative Cardamine Hirsuta Reveals How Adaptation, Demography, and Development Shape Diversity Patterns”. In: PLOS Biology 21.7 (Jul. 18, 2023), p. e3002191. ISSN: 1545-7885. DOI: 10.1371/journal.pbio.3002191. https://journals.plos.org/plosbiology/article?id=10.1371/journal.pbio.3002191 (visited on 07/24/2023).

[5] J. Botero, A. S. Sombolestani, M. Cnockaert, et al. “A Phylogenomic and Comparative Genomic Analysis of Commensalibacter, a Versatile Insect Symbiont”. In: Animal Microbiome 5.1 (Apr. 29, 2023), p. 25. ISSN: 2524-4671. DOI: 10.1186/s42523-023-00248-6. https://doi.org/10.1186/s42523-023-00248-6 (visited on 05/02/2023).

[6] I. N. Boys, A. G. Johnson, M. R. Quinlan, et al. “Structural Homology Screens Reveal Host-Derived Poxvirus Protein Families Impacting Inflammasome Activity”. In: Cell Reports 42.8 (Aug. 29, 2023), p. 112878. ISSN: 2211-1247. DOI: 10.1016/j.celrep.2023.112878. https://www.sciencedirect.com/science/article/pii/S2211124723008896 (visited on 07/30/2023).

[7] I. N. Boys, A. G. Johnson, M. Quinlan, et al. Structural Homology Screens Reveal Poxvirus-Encoded Proteins Impacting Inflammasome-Mediated Defenses. Feb. 27, 2023. https://www.biorxiv.org/content/10.1101/2023.02.26.529821v1 (visited on 03/02/2023). preprint.

[8] N. H. Buitendijk and B. A. Nolet. “Timing and Intensity of Goose Grazing: Implications for Grass Height and First Harvest”. In: Agriculture, Ecosystems & Environment 357 (Nov. 01, 2023), p. 108681. ISSN: 0167-8809. DOI: 10.1016/j.agee.2023.108681. https://www.sciencedirect.com/science/article/pii/S0167880923003407 (visited on 07/25/2023).

[9] M. E. Carey, Z. A. Dyson, D. J. Ingle, et al. “Global Diversity and Antimicrobial Resistance of Typhoid Fever Pathogens: Insights from a Meta-Analysis of 13,000 Salmonella Typhi Genomes”. In: eLife 12 (Sep. 12, 2023). Ed. by M. J. Bonten, J. W. van der Meer, M. J. Bonten and L. A. Cowley, p. e85867. ISSN: 2050-084X. DOI: 10.7554/eLife.85867. https://doi.org/10.7554/eLife.85867 (visited on 09/19/2023).

[10] H. Chen, G. Chew, N. Devapragash, et al. “The E3 Ubiquitin Ligase WWP2 Regulates Pro-Fibrogenic Monocyte Infiltration and Activity in Heart Fibrosis”. In: Nature Communications 13.1 (1 Nov. 30, 2022), p. 7375. ISSN: 2041-1723. DOI: 10.1038/s41467-022-34971-6. https://www.nature.com/articles/s41467-022-34971-6 (visited on 12/03/2022).

[11] T. Chen, Y. Lei, M. Li, et al. “Network Pharmacology to Unveil the Mechanism of Suanzaoren Decoction in the Treatment of Alzheimer’s with Diabetes”. In: Hereditas 161.1 (Jan. 03, 2024), p. 2. ISSN: 1601-5223. DOI: 10.1186/s41065-023-00301-z. pmid: 38167125.

[12] H. Danlin, T. Chao, S. Zhenjie, et al. “Potential Synergistic Regulation of Hsp70 and Antioxidant Enzyme Genes in Pyropia Yezoensis under High Temperature Stress”. In: Algal Research (Jan. 10, 2024), p. 103375. ISSN: 2211-9264. DOI: 10.1016/j.algal.2023.103375. https://www.sciencedirect.com/science/article/pii/S2211926423004083 (visited on 01/16/2024).

[13] X. Ding, K. Liu, Q. Yan, et al. “Sugar and Organic Acid Availability Modulate Soil Diazotroph Community Assembly and Species Co-Occurrence Patterns on the Tibetan Plateau”. In: Applied Microbiology and Biotechnology (Oct. 18, 2021). ISSN: 1432-0614. DOI: 10.1007/s00253-021-11629-9. https://doi.org/10.1007/s00253-021-11629-9 (visited on 10/21/2021).

[14] T. G. Drivas, A. Lucas, and M. D. Ritchie. “eQTpLot: A User-Friendly R Package for the Visualization of Colocalization between eQTL and GWAS Signals”. In: BioData Mining 14.1 (Jul. 17, 2021), p. 32. ISSN: 1756-0381. DOI: 10.1186/s13040-021-00267-6. https://doi.org/10.1186/s13040-021-00267-6 (visited on 07/21/2021).

[15] K. Giannakis, S. J. Arrowsmith, L. Richards, et al. “Evolutionary Inference across Eukaryotes Identifies Universal Features Shaping Organelle Gene Retention”. In: Cell Systems (Sep. 16, 2022). ISSN: 2405-4712. DOI: 10.1016/j.cels.2022.08.007. https://www.sciencedirect.com/science/article/pii/S2405471222003519 (visited on 09/19/2022).

[16] R. B. Gorodnichev, M. A. Kornienko, M. V. Malakhova, et al. “Isolation and Characterization of the First Zobellviridae Family Bacteriophage Infecting Klebsiella Pneumoniae”. In: International Journal of Molecular Sciences 24.4 (4 Jan. 2023), p. 4038. ISSN: 1422-0067. DOI: 10.3390/ijms24044038. https://www.mdpi.com/1422-0067/24/4/4038 (visited on 02/20/2023).

[17] M. C. Granovetter, L. Ettensohn, and M. Behrmann. “With Childhood Hemispherectomy, One Hemisphere Can Support—But Is Suboptimal for—Word and Face Recognition”. In: bioRxiv (Nov. 08, 2020), p. 2020.11.06.371823. DOI: 10.1101/2020.11.06.371823. https://www.biorxiv.org/content/10.1101/2020.11.06.371823v1 (visited on 03/03/2021).

[18] C. Higgs, L. S. Kumar, K. Stevens, et al. “Comparison of Contemporary Invasive and Non-Invasive Streptococcus Pneumoniae Isolates Reveals New Insights into Circulating Anti-Microbial Resistance Determinants”. In: Antimicrobial Agents and Chemotherapy 0.0 (Oct. 12, 2023), pp. e00785-23. DOI: 10.1128/aac.00785-23. https://journals.asm.org/doi/10.1128/aac.00785-23 (visited on 10/23/2023).

[19] C. Higgs, L. S. Kumar, K. Stevens, et al. “Population Structure, Serotype Distribution and Antibiotic Resistance of Streptococcus Pneumoniae Causing Invasive Disease in Victoria, Australia”. In: Microbial Genomics 9.7 (2023), p. 001070. ISSN: 2057-5858. DOI: 10.1099/mgen.0.001070. https://www.microbiologyresearch.org/content/journal/mgen/10.1099/mgen.0.001070 (visited on 07/25/2023).

[20] A. T. Hinsu, K. J. Panchal, R. J. Pandit, et al. “Characterizing Rhizosphere Microbiota of Peanut (Arachis Hypogaea L.) from Pre-Sowing to Post-Harvest of Crop under Field Conditions”. In: Scientific Reports 11.1 (1 Aug. 31, 2021), p. 17457. ISSN: 2045-2322. DOI: 10.1038/s41598-021-97071-3. https://www.nature.com/articles/s41598-021-97071-3 (visited on 09/06/2021).

[21] T. Hinzke, F. Tanneberger, C. Aggenbach, et al. “Response Patterns of Fen Sedges to a Nutrient Gradient Indicate Both Geographic Origin-Specific Genotypic Differences and Phenotypic Plasticity”. In: Wetlands 42.8 (Nov. 17, 2022), p. 113. ISSN: 1943-6246. DOI: 10.1007/s13157-022-01629-4. https://doi.org/10.1007/s13157-022-01629-4 (visited on 11/24/2022).

[22] M. Jenckel, I. Smith, T. King, et al. “Distribution and Genetic Diversity of Hepatitis E Virus in Wild and Domestic Rabbits in Australia”. In: Pathogens 10.12 (12 Dec. 2021), p. 1637. DOI: 10.3390/pathogens10121637. https://www.mdpi.com/2076-0817/10/12/1637 (visited on 12/21/2021).

[23] H. Jentsch and J. Weidinger. “Spatio-Temporal Analysis of Valley Wind Systems in the Complex Mountain Topography of the Rolwaling Himal, Nepal”. In: Atmosphere 13.7 (7 Jul. 2022), p. 1138. ISSN: 2073-4433. DOI: 10.3390/atmos13071138. https://www.mdpi.com/2073-4433/13/7/1138 (visited on 08/01/2022).

[24] B. Jiang, D. M. Weinstock, K. A. Donovan, et al. “ITK Degradation to Block T Cell Receptor Signaling and Overcome Therapeutic Resistance in T Cell Lymphomas”. In: Cell Chemical Biology 30.4 (Apr. 20, 2023), pp. 383-393.e6. ISSN: 2451-9456, 2451-9448. DOI: 10.1016/j.chembiol.2023.03.007. pmid: 37015223. https://www.cell.com/cell-chemical-biology/fulltext/S2451-9456(23)00086-7 (visited on 05/09/2023).

[25] X. Jin, F. B. Yu, J. Yan, et al. “Culturing of a Complex Gut Microbial Community in Mucin-Hydrogel Carriers Reveals Strain- and Gene-Associated Spatial Organization”. In: Nature Communications 14.1 (1 Jun. 14, 2023), p. 3510. ISSN: 2041-1723. DOI: 10.1038/s41467-023-39121-0. https://www.nature.com/articles/s41467-023-39121-0 (visited on 06/17/2023).

[26] P. M. Joubert and K. V. Krasileva. Distinct Genomic Contexts Predict Gene Presence-Absence Variation in Different Pathotypes of a Fungal Plant Pathogen. Feb. 17, 2023. https://www.biorxiv.org/content/10.1101/2023.02.17.529015v1 (visited on 02/20/2023). preprint.

[27] M. Jung, D. Wells, J. Rusch, et al. “Unified Single-Cell Analysis of Testis Gene Regulation and Pathology in Five Mouse Strains”. In: eLife 8 (Jun. 25, 2019). Ed. by D. Bourc’his, P. J. Wittkopp and S. Lukassen, p. e43966. ISSN: 2050-084X. DOI: 10.7554/eLife.43966. https://doi.org/10.7554/eLife.43966 (visited on 03/03/2021).

[28] T. Karasaki, D. A. Moore, S. Veeriah, et al. “Evolutionary Characterization of Lung Adenocarcinoma Morphology in TRACERx”. In: Nature Medicine (Apr. 12, 2023), pp. 1-13. ISSN: 1546-170X. DOI: 10.1038/s41591-023-02230-w. https://www.nature.com/articles/s41591-023-02230-w (visited on 04/14/2023).

[29] N. Khan, H. T. T. Nguyen, S. Galelli, et al. “Increasing Drought Risks Over the Past Four Centuries Amidst Projected Flood Intensification in the Kabul River Basin (Afghanistan and Pakistan)—Evidence From Tree Rings”. In: Geophysical Research Letters 49.24 (2022), p. e2022GL100703. ISSN: 1944-8007. DOI: 10.1029/2022GL100703. https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2022GL100703 (visited on 05/09/2023).

[30] M. Kornienko, D. Bespiatykh, M. Malakhova, et al. “PCR Assay for Rapid Taxonomic Differentiation of Virulent Staphylococcus Aureus and Klebsiella Pneumoniae Bacteriophages”. In: International Journal of Molecular Sciences 24.5 (5 Jan. 2023), p. 4483. ISSN: 1422-0067. DOI: 10.3390/ijms24054483. https://www.mdpi.com/1422-0067/24/5/4483 (visited on 03/02/2023).

[31] S. Kudrenko, J. Vollering, A. Zedrosser, et al. “Walking on the Dark Side: Anthropogenic Factors Limit Suitable Habitat for Gray Wolf (Canis Lupus) in a Large Natural Area Covering Belarus and Ukraine”. In: Global Ecology and Conservation (Jul. 24, 2023), p. e02586. ISSN: 2351-9894. DOI: 10.1016/j.gecco.2023.e02586. https://www.sciencedirect.com/science/article/pii/S2351989423002214 (visited on 07/27/2023).

[32] A. Lan, K. Kang, S. Tang, et al. “Fine-Scale Population Structure and Demographic History of Han Chinese Inferred from Haplotype Network of 111,000 Genomes”. In: bioRxiv (Jul. 04, 2020), p. 2020.07.03.166413. DOI: 10.1101/2020.07.03.166413. https://www.biorxiv.org/content/10.1101/2020.07.03.166413v2 (visited on 03/03/2021).

[33] Z. Lapp, R. Crawford, A. Miles-Jay, et al. “Regional Spread of blaNDM-1-containing Klebsiella Pneumoniae ST147 in Post-Acute Care Facilities”. In: Clinical Infectious Diseases (ciab457 May. 17, 2021). ISSN: 1058-4838. DOI: 10.1093/cid/ciab457. https://doi.org/10.1093/cid/ciab457 (visited on 05/21/2021).

[34] L. S. H. Lee and C. Y. Jim. “Thermal and Humidification Effects of a Swimming Pool in Hong Kong’s Humid-Subtropical Summer”. In: Sustainable Cities and Society (Jul. 22, 2023), p. 104816. ISSN: 2210-6707. DOI: 10.1016/j.scs.2023.104816. https://www.sciencedirect.com/science/article/pii/S2210670723004274 (visited on 07/25/2023).

[35] Z. Liang, T. Liu, Q. Li, et al. “Deciphering the Functional Landscape of Phosphosites with Deep Neural Network”. In: Cell Reports 42.9 (Sep. 26, 2023). ISSN: 2211-1247. DOI: 10.1016/j.celrep.2023.113048. pmid: 37659078. https://www.cell.com/cell-reports/abstract/S2211-1247(23)01059-8 (visited on 09/19/2023).

[36] X. Lin, Z. Sha, J. Trimpert, et al. “The NSP4 T492I Mutation Increases SARS-CoV-2 Infectivity by Altering Non-Structural Protein Cleavage”. In: Cell Host & Microbe (Jul. 03, 2023). ISSN: 1931-3128. DOI: 10.1016/j.chom.2023.06.002. https://www.sciencedirect.com/science/article/pii/S1931312823002536 (visited on 07/06/2023).

[37] J. Ma, X. Zhu, R. Hu, et al. “A Systematic Review, Meta-Analysis and Meta-Regression of the Global Prevalence of Foodborne Vibrio Spp. Infection in Fishes: A Persistent Public Health Concern”. In: Marine Pollution Bulletin 187 (Feb. 01, 2023), p. 114521. ISSN: 0025-326X. DOI: 10.1016/j.marpolbul.2022.114521. https://www.sciencedirect.com/science/article/pii/S0025326X22012036 (visited on 01/10/2023).

[38] D. G. Maghini, M. Dvorak, A. Dahlen, et al. “Quantifying Bias Introduced by Sample Collection in Relative and Absolute Microbiome Measurements”. In: Nature Biotechnology (Apr. 27, 2023), pp. 1-11. ISSN: 1546-1696. DOI: 10.1038/s41587-023-01754-3. https://www.nature.com/articles/s41587-023-01754-3 (visited on 05/02/2023).

[39] E. Merino Tejero, D. Lashgari, R. García-Valiente, et al. “Multiscale Modeling of Germinal Center Recapitulates the Temporal Transition From Memory B Cells to Plasma Cells Differentiation as Regulated by Antigen Affinity-Based Tfh Cell Help”. In: Frontiers in Immunology 11 (Feb. 05, 2021). ISSN: 1664-3224. DOI: 10.3389/fimmu.2020.620716. pmid: 33613551. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7892951/ (visited on 03/03/2021).

[40] I. Mokrousov, A. Vyazovaya, E. Shitikov, et al. “Insight into Pathogenomics and Phylogeography of Hypervirulent and Highly-Lethal Mycobacterium Tuberculosis Strain Cluster”. In: BMC Infectious Diseases 23.1 (Jun. 23, 2023), p. 426. ISSN: 1471-2334. DOI: 10.1186/s12879-023-08413-7. https://doi.org/10.1186/s12879-023-08413-7 (visited on 06/28/2023).

[41] G. Papacharalampous, H. Tyralis, S. M. Papalexiou, et al. “Global-Scale Massive Feature Extraction from Monthly Hydroclimatic Time Series: Statistical Characterizations, Spatial Patterns and Hydrological Similarity”. In: Science of The Total Environment 767 (May. 01, 2021), p. 144612. ISSN: 0048-9697. DOI: 10.1016/j.scitotenv.2020.144612. https://www.sciencedirect.com/science/article/pii/S0048969720381432 (visited on 03/03/2021).

[42] C. Plaza, P. García-Palacios, A. A. Berhe, et al. “Ecosystem Productivity Has a Stronger Influence than Soil Age on Surface Soil Carbon Storage across Global Biomes”. In: Communications Earth & Environment 3.1 (1 Oct. 07, 2022), pp. 1-8. ISSN: 2662-4435. DOI: 10.1038/s43247-022-00567-7. https://www.nature.com/articles/s43247-022-00567-7 (visited on 10/12/2022).

[43] C. Plaza, P. García-Palacios, A. A. Berhe, et al. “Ecosystem Productivity Has a Stronger Influence than Soil Age on Surface Soil Carbon Storage across Global Biomes”. In: Communications Earth & Environment 3.1 (1 Oct. 07, 2022), pp. 1-8. ISSN: 2662-4435. DOI: 10.1038/s43247-022-00567-7. https://www.nature.com/articles/s43247-022-00567-7 (visited on 10/31/2022).

[44] P. Pottier, H. Lin, R. R. Y. Oh, et al. “A Comprehensive Database of Amphibian Heat Tolerance”. In: Scientific Data 9.1 (1 Oct. 04, 2022), p. 600. ISSN: 2052-4463. DOI: 10.1038/s41597-022-01704-9. https://www.nature.com/articles/s41597-022-01704-9 (visited on 10/08/2022).

[45] J. M. Quilty, A. E. Sikorska-Senoner, and D. Hah. “A Stochastic Conceptual-Data-Driven Approach for Improved Hydrological Simulations”. In: Environmental Modelling & Software (Jan. 16, 2022), p. 105326. ISSN: 1364-8152. DOI: 10.1016/j.envsoft.2022.105326. https://www.sciencedirect.com/science/article/pii/S1364815222000329 (visited on 01/19/2022).

[46] D. L. Rios, P. C. L. da Silva, C. S. S. Moura, et al. “Comparative Metatranscriptome Analysis of Brazilian Milk and Water Kefir Beverages”. In: International Microbiology (Sep. 28, 2023). ISSN: 1618-1905. DOI: 10.1007/s10123-023-00431-4. https://doi.org/10.1007/s10123-023-00431-4 (visited on 10/03/2023).

[47] H. Rodenhizer, F. Belshe, G. Celis, et al. “Abrupt Permafrost Thaw Accelerates Carbon Dioxide and Methane Release at a Tussock Tundra Site”. In: Arctic, Antarctic, and Alpine Research 54.1 (Dec. 31, 2022), pp. 443-464. ISSN: 1523-0430. DOI: 10.1080/15230430.2022.2118639. https://doi.org/10.1080/15230430.2022.2118639 (visited on 10/04/2022).

[48] A. Rutz, M. Sorokina, J. Galgonek, et al. “Open Natural Products Research: Curation and Dissemination of Biological Occurrences of Chemical Structures through Wikidata”. In: bioRxiv (Mar. 01, 2021), p. 2021.02.28.433265. DOI: 10.1101/2021.02.28.433265. https://www.biorxiv.org/content/10.1101/2021.02.28.433265v1 (visited on 03/07/2021).

[49] A. Saha, A. Bellucci, S. Fratini, et al. “Ecological Factors and Parity Mode Correlate with Genome Size Variation in Squamate Reptiles”. In: BMC Ecology and Evolution 23.1 (Dec. 05, 2023), p. 69. ISSN: 2730-7182. DOI: 10.1186/s12862-023-02180-4. https://doi.org/10.1186/s12862-023-02180-4 (visited on 12/16/2023).

[50] M. R. Scharn, M. C. G. Brachmann, M. A. Patchett, et al. Vegetation Responses to 26 Years of Warming at Latnjajaure Field Station, Northern Sweden. https://doi.org/10.1139/AS-2020-0042. Apr. 01, 2021. https://cdnsciencepub.com/doi/abs/10.1139/AS-2020-0042 (visited on 04/05/2021).

[51] L. Seep, Z. Razaghi-Moghadam, and Z. Nikoloski. “Reaction Lumping in Metabolic Networks for Application with Thermodynamic Metabolic Flux Analysis”. In: Scientific Reports 11.1 (1 Apr. 20, 2021), p. 8544. ISSN: 2045-2322. DOI: 10.1038/s41598-021-87643-8. https://www.nature.com/articles/s41598-021-87643-8 (visited on 04/23/2021).

[52] O. Seppälä. “Spatial and Temporal Drivers of Soil Respiration in a Tundra Environment”. MA Thesis. FACULTY OF SCIENCE DEPARTMENT OF GEOSCIENCES AND GEOGRAPHY GEOGRAPHY: UNIVERSITY OF HELSINKI, 2020.

[53] L. Shah, C. A. Arnillas, and G. B. Arhonditsis. “Characterizing Temporal Trends of Meteorological Extremes in Southern and Central Ontario, Canada”. In: Weather and Climate Extremes (Jan. 25, 2022), p. 100411. ISSN: 2212-0947. DOI: 10.1016/j.wace.2022.100411. https://www.sciencedirect.com/science/article/pii/S2212094722000056 (visited on 01/29/2022).

[54] S. A. Simon, K. Schmidt, L. Griesdorn, et al. Dancing the Nanopore Limbo – Nanopore Metagenomics from Small DNA Quantities for Bacterial Genome Reconstruction. Feb. 16, 2023. https://www.biorxiv.org/content/10.1101/2023.02.16.527874v1 (visited on 02/20/2023). preprint.

[55] C. C. Smith, S. Entwistle, C. Willis, et al. “Landscape and Selection of Vaccine Epitopes in SARS-CoV-2”. In: bioRxiv (Jun. 04, 2020). DOI: 10.1101/2020.06.04.135004. pmid: 32577654. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7302209/ (visited on 03/03/2021).

[56] F. St-Onge, M. Javanray, A. Pichet Binette, et al. “Functional Connectome Fingerprinting across the Lifespan”. In: Network Neuroscience (May. 04, 2023), pp. 1-55. ISSN: 2472-1751. DOI: 10.1162/netn_a_00320. https://doi.org/10.1162/netn_a_00320 (visited on 05/09/2023).

[57] S. N. Thiede, E. S. Snitkin, W. Trick, et al. “Genomic Epidemiology Suggests Community Origins of Healthcare-Associated USA300 MRSA”. In: The Journal of Infectious Diseases (Feb. 16, 2022), p. jiac056. ISSN: 0022-1899. DOI: 10.1093/infdis/jiac056. https://doi.org/10.1093/infdis/jiac056 (visited on 02/26/2022).

[58] A. V. Thorn, F. M. Aarestrup, and P. Munk. “Flankophile: A Bioinformatic Pipeline for Prokaryotic Genomic Synteny Analysis”. In: Microbiology Spectrum (Dec. 12, 2023), p. e0241323. ISSN: 2165-0497. DOI: 10.1128/spectrum.02413-23. pmid: 38084973.

[59] A. Torres-Espín, A. Chou, J. R. Huie, et al. “Reproducible Analysis of Disease Space via Principal Components Using the Novel R Package syndRomics”. In: eLife 10 (Jan. 14, 2021). Ed. by M. Zaidi and M. Barton, p. e61812. ISSN: 2050-084X. DOI: 10.7554/eLife.61812. https://doi.org/10.7554/eLife.61812 (visited on 03/03/2021).

[60] C. Wang, X. Zhao, H. Zhang, et al. “Comprehensive Analysis of Immune-Related Genes Associated with the Microenvironment of Patients with Unexplained Infertility”. In: Annals of Translational Medicine 11.2 (2 Jan. 2023), pp. 84-84. ISSN: 2305-5847, 2305-5839. DOI: 10.21037/atm-22-5810. https://atm.amegroups.org/article/view/108642 (visited on 02/12/2023).

[61] L. Weidenauer and M. Quadroni. “Phosphorylation in the Charged Linker Modulates Interactions and Secretion of Hsp90β”. In: Cells 10.7 (7 Jul. 2021), p. 1701. DOI: 10.3390/cells10071701. https://www.mdpi.com/2073-4409/10/7/1701 (visited on 07/08/2021).

[62] D. Wendisch, O. Dietrich, T. Mari, et al. “SARS-CoV-2 Infection Triggers Profibrotic Macrophage Responses and Lung Fibrosis”. In: Cell (Nov. 27, 2021). ISSN: 0092-8674. DOI: 10.1016/j.cell.2021.11.033. https://www.sciencedirect.com/science/article/pii/S0092867421013830 (visited on 12/11/2021).

[63] R. Woyda, A. Oladeinde, and Z. Abdo. “Chicken Production and Human Clinical Escherichia Coli Isolates Differ in Their Carriage of Antimicrobial Resistance and Virulence Factors”. In: Applied and Environmental Microbiology 0.0 (Jan. 18, 2023), pp. e01167-22. DOI: 10.1128/aem.01167-22. https://journals.asm.org/doi/abs/10.1128/aem.01167-22 (visited on 01/25/2023).

[64] R. J. Wright, M. G. I. Langille, and T. R. Walker. “Food or Just a Free Ride? A Meta-Analysis Reveals the Global Diversity of the Plastisphere”. In: The ISME Journal 15.3 (3 Mar. 2021), pp. 789-806. ISSN: 1751-7370. DOI: 10.1038/s41396-020-00814-9. https://www.nature.com/articles/s41396-020-00814-9 (visited on 03/03/2021).

[65] P. Wu, C. Chang, G. Zhu, et al. “Network Pharmacology Study of Bioactive Components and Molecular Mechanisms of the Glycoside Fraction from $<$em$>$Picrorhiza Scrophulariiflora$<$/Em$>$ Against Experimental Colitis”. In: Drug Design, Development and Therapy 17 (May. 23, 2023), pp. 1531-1546. DOI: 10.2147/DDDT.S407339. https://www.dovepress.com/network-pharmacology-study-of-bioactive-components-and-molecular-mecha-peer-reviewed-fulltext-article-DDDT (visited on 05/28/2023).

[66] T. Wyenberg-Henzler, R. T. Patterson, and J. C. Mallon. “Ontogenetic Dietary Shifts in North American Hadrosaurids”. In: Cretaceous Research (Feb. 23, 2022), p. 105177. ISSN: 0195-6671. DOI: 10.1016/j.cretres.2022.105177. https://www.sciencedirect.com/science/article/pii/S0195667122000416 (visited on 02/26/2022).

[67] L. Xie, H. Liu, Z. You, et al. “Comprehensive Spatiotemporal Mapping of Single-Cell Lineages in Developing Mouse Brain by CRISPR-based Barcoding”. In: Nature Methods (Jul. 17, 2023), pp. 1-12. ISSN: 1548-7105. DOI: 10.1038/s41592-023-01947-3. https://www.nature.com/articles/s41592-023-01947-3 (visited on 07/24/2023).

[68] M. Xie, B. Cheng, S. Yu, et al. “Cuproptosis-Related MiR-21-5p/FDX1 Axis in Clear Cell Renal Cell Carcinoma and Its Potential Impact on Tumor Microenvironment”. In: Cells 12.1 (Dec. 31, 2022), p. 173. ISSN: 2073-4409. DOI: 10.3390/cells12010173. pmid: 36611966.

[69] Y. Xu, M. Price, P. Que, et al. “Ecological Predictors of Interspecific Variation in Bird Bill and Leg Lengths on a Global Scale”. In: Proceedings of the Royal Society B: Biological Sciences 290.2003 (Jul. 26, 2023), p. 20231387. DOI: 10.1098/rspb.2023.1387. https://royalsocietypublishing.org/doi/abs/10.1098/rspb.2023.1387 (visited on 07/30/2023).

[70] A. Yan, J. Butcher, D. Mack, et al. “Virome Sequencing of the Human Intestinal Mucosal–Luminal Interface”. In: Frontiers in Cellular and Infection Microbiology 10 (Oct. 22, 2020). ISSN: 2235-2988. DOI: 10.3389/fcimb.2020.582187. pmid: 33194818. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7642909/ (visited on 03/03/2021).

[71] P. Zannini, F. Frascaroli, J. Nascimbene, et al. “Sacred Natural Sites and Biodiversity Conservation: A Systematic Review”. In: Biodiversity and Conservation (Sep. 30, 2021). ISSN: 1572-9710. DOI: 10.1007/s10531-021-02296-3. https://doi.org/10.1007/s10531-021-02296-3 (visited on 10/04/2021).

[72] H. L. Zhang, K. J. Gontjes, J. H. Han, et al. “Characterization of Resistance to Newer Antimicrobials among Carbapenem-Resistant Klebsiella Pneumoniae in the Post–Acute-Care Setting”. In: Infection Control & Hospital Epidemiology (Jul. 28, 2022), pp. 1-4. ISSN: 0899-823X, 1559-6834. DOI: 10.1017/ice.2022.185. https://www.cambridge.org/core/journals/infection-control-and-hospital-epidemiology/article/abs/characterization-of-resistance-to-newer-antimicrobials-among-carbapenemresistant-klebsiella-pneumoniae-in-the-postacutecare-setting/33D7F100FEF2CA18FBED645D8A268EA8#supplementary-materials (visited on 08/01/2022).

[73] X. Zhang, X. Yu, Z. Yu, et al. “Network Pharmacology and Bioinformatics to Identify Molecular Mechanisms and Therapeutic Targets of Ruyi Jinhuang Powder in the Treatment of Monkeypox”. In: Medicine 102.17 (Apr. 25, 2023), p. e33576. DOI: 10.1097/MD.0000000000033576. https://journals.lww.com/md-journal/Fulltext/2023/04250/Network_pharmacology_and_bioinformatics_to.34.aspx (visited on 05/02/2023).

[74] P. Zhu, W. Liu, X. Zhang, et al. “Correlated Evolution of Social Organization and Lifespan in Mammals”. In: Nature Communications 14.1 (1 Jan. 31, 2023), p. 372. ISSN: 2041-1723. DOI: 10.1038/s41467-023-35869-7. https://www.nature.com/articles/s41467-023-35869-7 (visited on 02/04/2023).

Usage

The main function is new_scale() and its aliases new_scale_color() and new_scale_fill(). When added to a plot, every geom added after them will use a different scale.

As an example, let’s overlay some measurements over a contour map of topography using the beloved volcano.

library(ggplot2)
library(ggnewscale)
# Equivalent to melt(volcano)
topography <- expand.grid(x = 1:nrow(volcano),
                          y = 1:ncol(volcano))
topography$z <- c(volcano)

# point measurements of something at a few locations
set.seed(42)
measurements <- data.frame(x = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = rnorm(30))

ggplot(mapping = aes(x, y)) +
  geom_contour(data = topography, aes(z = z, color = stat(level))) +
  # Color scale for topography
  scale_color_viridis_c(option = "D") +
  # geoms below will use another color scale
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(color = thing)) +
  # Color scale applied to geoms added after new_scale_color()
  scale_color_viridis_c(option = "A")
#> Warning: `stat(level)` was deprecated in ggplot2 3.4.0.
#> ℹ Please use `after_stat(level)` instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.

If you want to create new scales for other aes, you can call new_scale with the name of the aes. For example, use

new_scale("linetype")

to add multiple linetype scales.

ggnewscale's People

Contributors

eliocamp avatar olivroy avatar teunbrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ggnewscale's Issues

Add ability to name scales

From #48

A possible fix is to change the function to: new_scale("alpha", "some.name") instead of only adding the _new (or leaving it as the default behavior) and then using that name in the guides will probably work

Show specific legend with ggnewscale

ggnewscale is really a helpful package, but I have a little question about the package is it possible to show specific legend?

Such as only show the temp legend on the plot and drop the type legend. I know we can drop it using guide = 'none' in new_scale_fill() and new_scale_color(), but in my code I use new_scale('fill').

Any help will be highly appreciated!

library(scatterpie)
library(tidyverse)
library(geosphere)
library(ggnewscale)
us <- map_data('state') %>% as_tibble()

n = length(unique(us$region))

# creat fake mapping data

temperature_data <- tibble(region = unique(us$region),
                           temp = rnorm(n = n))

coords <- us %>% select(long, lat, region) %>% distinct(region, .keep_all = T)


category_data <- tibble(region = unique(us$region),
                        cat_1 = sample(1:100, size = n),
                        cat_2 = sample(1:100, size = n),
                        cat_3 = sample(1:100, size = n)) %>% left_join(coords)


us <- left_join(us, temperature_data)




p + geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
  new_scale('fill') +
  geom_scatterpie(data = category_data,
                  aes(long, lat),
                  cols = c("cat_1", "cat_2", "cat_3"), 
                  alpha = 0.5)


Linetype guides got mixed when vertical and horizontal lines are combined

Hi, I've discovered your package recently and it helped in recent issue of mine. I'm building a plot which combines some basic line and arbitrary straight lines. Each of the line should be described in the legend with appropriate color/type/orientation.
It works excellent when the lines differs only by colour, otherwise it got little mixed.

library(ggplot2) 
library(ggnewscale) 
gg <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) +     
    geom_line(aes(group=Species, color = Species)) +    
    facet_grid(.~Species)  
    
hor <- data.frame(yintercept = c(4, 5), horizontal = factor(c("h1", "h2")))   
vert <- data.frame(xintercept = 6, vertical = factor("v1"))  

gg +   
    new_scale_color() +   
    geom_hline(aes(yintercept = yintercept, colour = horizontal), data = hor, show.legend = TRUE, linetype = "solid") + 
    scale_color_manual(name="Horizontal lines", values = c("red","darkred")) + 
    new_scale_color() +
    geom_vline(aes(xintercept = xintercept, colour = vertical), data = vert, show.legend = TRUE, linetype = "solid") + 
    scale_color_manual(name="Vertical lines", values = "green") 

image


I have tried to fix it though the guides but it doesn't help

gg +   
    new_scale("linetype") +
    geom_hline(aes(yintercept = yintercept, colour = horizontal), data = hor, show.legend = TRUE, linetype = "dashed") + 
    scale_linetype_manual(name="Horizontal lines", values = c("red","darkred")) + 
    guides(
        linetype = guide_legend(override.aes = list(
          color = c("red","darkred"),
          orientation = c("horizontal", "horizontal")
      ))
    ) +
    new_scale("linetype") +
    geom_vline(aes(xintercept = xintercept, colour = vertical), data = vert, show.legend = TRUE, linetype = "dashed") + 
    scale_linetype_manual(name="Vertical lines", values = "green") +
    guides(
        linetype = guide_legend(override.aes = list(
          color = "green",
          orientation = "vertical"
      ))
    ) 

image

Do you have a plan to separate the other line-attributes?

Regards,
DK

Can't have discrete scale before continuous scale

Based on the example, I came upon a bug. Converting the color for the points to a discrete scale works, but only as long as it is the second plot.
First do this (after running the earlier code in the example):

measurements <- data.frame(x = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = sample(1:4, 30, replace = T))

Then, if you put the continuous fill first, then add a discrete fill, it works:

ggplot(mapping = aes(x, y)) +
    geom_contour(data = topography, aes(z = z, color = stat(level))) +
    # Color scale for topography
    scale_color_viridis_c(option = "D") +
    # geoms below will use another color scale
    new_scale_color() +
    geom_point(data = measurements, size = 3, aes(color = as.factor(thing)))

But if you put the discrete fill first:

ggplot(mapping = aes(x, y)) +
    geom_point(data = measurements, size = 3, aes(color = as.factor(thing))) +
    # Color scale for topography
    scale_color_viridis_c(option = "D") +
    # geoms below will use another color scale
    new_scale_color() +
    geom_contour(data = topography, aes(z = z, color = stat(level)))

it gives an error:

Error: Discrete value supplied to continuous scale

Compatibility with custom geoms

Hi,

I really like your package. Your effort is really much appreciated!

However when combining my custom geom (e.g. geom_mycustom()) with new_scale_fill() I encounter an problem, which I'd like to point out in the following
The problem is that the setup_data() function of the associated stat looks like this:

setup_data = function(data, params) {
  data <- plyr::ddply(data, c("x", "fill"), within,
                      # Assign the range of `y` to the newly created column `range`.
                      assign("range", list(range(y))))
}

The problem is that the column fill becomes fill_new in the second iteration due to new_scale_fill() when the whole plot is built again. This results in the following error:

Error in unique.default(x) :
unique() applies only to vectors

A solution to that is to simply change setup_data as follow:

setup_data = function(data, params) {
  fill_name <- str_subset(names(data), "fill")
  data <- plyr::ddply(data, c("x", fill_name), within,
                      # Assign the range of `y` to the newly created column `range`.
                      assign("range", list(range(y))))
}

Just out of curiosity an because I have a few more places where I use plyr::ddply() I was wondering if there might be another way to resolve this problem.

Happy to hear from you.
Best regards

new_scale_fill() changes colour to previous geom

I'm trying to plot a spatial heatmap from various x y points that are separed in 2 categories. I wish to plot both categories with stat_density_2d in different colors (green and red).

However, whenever I add a new_scale_fill(), the background color of previously plotted geom change colors.

For exemple, regular plot:

p <- ggplot() +
  aes(long, lat, group = group) +
  geom_polygon(data = hydro.df, fill = "#d9e2ea", color = NA) +
  geom_polygon(data = iles.df, fill = "white", color = NA) +
  geom_path(data = routes.maj.df,
            #aes(long, lat, group = group),
            colour = rgb(0.9, 0.9, 0.9), size = 0.25) +
  geom_polygon(data = villes.df, fill = NA, color = "red", size = 0.2) +
  stat_density_2d(
    data = subset(av.desav, classement == "avantage"),
    aes(x = x, y = y, group = NA, 
      fill = ..level.., alpha = ..level..),
    geom = "polygon") + 
  scale_fill_gradient("< -5 min.",
    low = "white", high = rgb(10, 255, 10, maxColorValue = 255),
    labels = NULL) +
  guides(alpha = F) +
  coord_fixed(ratio = 1, xlim = x.lim, ylim = y.lim, expand = F) +
  theme_void()

plot(p)

gives this:
image

But when I try to add a scale to plot another stat_density, this is what I get:

plot(p + new_scale_fill() #+
  # not plotted
  # stat_density_2d(data = subset(av.desav, classement == "desavantage"),
  #                 aes(x = x, y = y,
  #                     fill = ..level.., alpha = ..level..),
  #                 geom = "polygon") +
  # scale_fill_gradient("> 5 min.",
  #                     low = "white", high = rgb(255,10,10, maxColorValue = 255),
  #                     labels = NULL)
)

image

The various geom_polygon data come from shapefiles. I don't know if that could be the problem.
Not sure if it's a bug or something I'm not doing right.

Thanks for your help!

Multiple new_scale_fill doesn't work.

Hello. I ran into a problem with using multiple new_scale_fill. It doesn't seems to work for me when I used more than two. Please see the example belows.

plot_data <-
  data.table(X = c(rnorm(300, 5, 2), rnorm(300,  5, 2),rnorm(300,  5, 2),rnorm(300,  5, 2)),
             Y = c(rnorm(300, 5, 1), rnorm(300, 10, 1),rnorm(300, 15, 1),rnorm(300, 20, 1)),
             Label = c(rep('A', 300), rep('B', 300), rep('C', 300), rep('D', 300)))

Using fill under ggplot. There's 4 groups.

ggplot(data=plot_data, aes(x=X, y=Y,fill=Label)) + 
  geom_bin2d() 

image

Using a single new_scale_fill

ggplot() +
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="A"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "red", high = "white")

image

Using two new_scale_fill

ggplot() +
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="A"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "red", high = "white")+
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="B"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "green", high = "white") 

image

Using three new_scale_fill

ggplot() +
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="A"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "red", high = "white")+
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="B"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "green", high = "white") +
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="C"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "blue", high = "white") 

image
Using four new_scale_fill

ggplot() +
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="A"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "red", high = "white")+
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="B"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "green", high = "white") +
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="C"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "blue", high = "white") +
  
  new_scale_fill() +
  geom_bin2d(data=plot_data[Label=="D"],aes(x=X, y=Y))+
  scale_fill_continuous(low = "purple", high = "white")

image

I'm taking this approach because I want to use new_scale_fill in a for loop situation. Such as below.

Main=ggplot()

for(count in 1:4){
  Main =Main + new_scale_fill() +
  geom_bin2d(data=plot_data[Label==Group_Information[count]],aes(x=X, y=Y))+
  scale_fill_continuous(low = Colours[count], high = "white")
}
Main
#The output is the same as the figure above.

As you can see, when using multiple new_scale_fill, the output was not what I was expecting, something similar to the first figure. I tried going through stackoverflow.com, but most example are only using two new_scale_fill.

sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=English_Malaysia.1252  LC_CTYPE=English_Malaysia.1252    LC_MONETARY=English_Malaysia.1252
[4] LC_NUMERIC=C                      LC_TIME=English_Malaysia.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggnewscale_0.4.7  ggplot2_3.3.5     data.table_1.14.0

loaded via a namespace (and not attached):
 [1] knitr_1.37       magrittr_2.0.1   tidyselect_1.1.1 munsell_0.5.0    colorspace_2.0-1 R6_2.5.0        
 [7] rlang_0.4.11     fansi_0.5.0      dplyr_1.0.6      tools_4.0.2      grid_4.0.2       gtable_0.3.0    
[13] xfun_0.29        utf8_1.2.1       DBI_1.1.1        withr_2.4.2      ellipsis_0.3.2   digest_0.6.27   
[19] assertthat_0.2.1 tibble_3.1.2     lifecycle_1.0.0  crayon_1.4.1     farver_2.1.0     purrr_0.3.4     
[25] vctrs_0.3.8      glue_1.4.2       labeling_0.4.2   compiler_4.0.2   pillar_1.6.1     generics_0.1.0  
[31] scales_1.1.1     pkgconfig_2.0.3 

Vertically align two legend groups

Hi Elio,
I have two fill legend groups new_scale(), is there a simple way to align them vertically on the top of the plot? I can't figure it out.
Thanks

isFALSE and isTRUE don't exist for older R

isFALSE and isTRUE were introduced to base in (I believe) R 3.5. I happen to be using an old R (3.4) so I am getting errors along the lines of:

Error in isFALSE(scale$guide) : could not find function "isFALSE"

Which is not a major headache, but it took a little while to figure out. I guess you could either specify

Depends: R (>= 3.5)

in the DESCRIPTION file (though then the package won't be usable by anyone pre 3.5), or define your own isFALSE and isTRUE functions.

Possibility to remove individual guides

Hi,
I love your package. I use the second scale to draw a region based color-coded background. However, the values are not meaningful for the viewer. I would like to hide the guide for only one of the colors. Is this somehow possible?

Thanks so much for this package. :)

ggnewscale only works with ggmap when extent = "normal"

I've been experimenting with ggnewscale and ggmap, and it seems to work provided you define extent = "normal". If you don't set the extent, it will default to extent = "panel", which causes it to fail with Error in get(as.character(FUN), mode = "function", envir = envir) : object 'guide_none' of mode 'function' was not found like in Issue #2. The same happens when extent = "device". See below; NB for ggmap you now need an API key to retrieve maps. Not sure why this happens but thought I would mention it in case someone else had insight, and because the default setting for ggmap doesn't work.

library(ggplot2)
library(ggmap)
library(ggnewscale)
#register_google(key = "") Must have API Key
berkeley <- get_map(location = c(-122.261021,37.871880), zoom = 16, maptype = "satellite")
# make some fake spatial data
mu <- c(-122.261021,37.871880)
measurements <- data.frame(x = runif(30*3, mu[1]-0.005, mu[1]+0.005),
                           y = runif(30*3, mu[2]-0.005, mu[2]+0.005),
                           thing1 = rnorm(30))
measurements2 <- data.frame(x = runif(30*3, mu[1]-0.005, mu[1]+0.005),
                            y = runif(30*3, mu[2]-0.005, mu[2]+0.005),
                            thing2 = rnorm(30))
#Works
ggmap(berkeley, extent = "normal") + 
  geom_point(data = measurements, aes(x, y, color = thing1)) +
  scale_color_viridis_c(option = "D") +
  new_scale_color() +
  geom_point(data = measurements2, aes(x, y, color = thing2)) +
  scale_color_viridis_c(option = "A")
#Fails
ggmap(berkeley, extent = "device") + 
  geom_point(data = measurements, aes(x, y, color = thing1)) +
  scale_color_viridis_c(option = "D") +
  new_scale_color() +
  geom_point(data = measurements2, aes(x, y, color = thing2)) +
  scale_color_viridis_c(option = "A")
#Fails
ggmap(berkeley, extent = "panel") + 
  geom_point(data = measurements, aes(x, y, color = thing1)) +
  scale_color_viridis_c(option = "D") +
  new_scale_color() +
  geom_point(data = measurements2, aes(x, y, color = thing2)) +
  scale_color_viridis_c(option = "A")

new scale for x/y?

Thanks for this great packge!

This would cool if it worked - as it would allow adding a secondary y-axis very easily (compared to the current native method...)

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.2

ggplot(mtcars, aes(hp, mpg)) + 
  geom_point(color = "red") + 
  ggnewscale::new_scale("y") + 
  geom_point(aes(y = drat), color = "blue")
#> Scale for 'y_new' is already present. Adding another scale for 'y_new', which
#> will replace the existing scale.
#> Error in `check_required_aesthetics()`:
#> ! new_geom_point requires the following missing aesthetics: y

Created on 2022-03-24 by the reprex package (v2.0.1)

Issue When Trying to Employ `guide_colourbar` ::::: v0.4.8

Hello @eliocamp,

Thanks a lot for the great tool.

I am running into a problem when I try to call guide_colourbar together with new_scale_fill(). I am not sure if the program is really designed to cover this possibility but it would be lovely if it were.

ggplot() +
 geom_raster(data = Salinity_df, aes(x = x, y = y, fill = Present.Surface.Salinity.Mean)) +
 scale_fill_gradient2(low = "#f0f0f0", mid = "#969696", high = "#252525", midpoint = 21, n.breaks = 5) +
 guides(fill = guide_colourbar(title = "Salinity", title.theme = element_text(size = 16, face = "bold"),
                               label.theme = element_text(size = 14, face = "bold"), label.position = "top",
                               barwidth = 10.7, barheight = 1, order = 1, frame.linetype = 1, frame.colour = "#000000",
                               ticks.colour = "#000000", direction = "horizontal")) +
 geom_sf(data = Global, fill = "#fff7f3", colour = "#000000") +
 new_scale_fill() +
 geom_star(data = Coors_Grouped, aes(x = Longitude, y = Latitude, starshape = Group, fill = BioState),
           colour = "#000000", size = 6)
Error in `guides_train()`:
! Guide 'colorbar' cannot be used for 'fill_new'.

May I ask if you would see any potential solution here?

Many thanks in advance, George.

ggnewscale doesn't work with scale_continuous or scale_discrete families

The example in the readme works fine for me, but as soon as I introduce any function of the scale_continuous family or scale_discrete family like this:

library(ggplot2)
library(ggnewscale)
# Equivalent to melt(volcano)
topography <- expand.grid(x = 1:nrow(volcano),
                          y = 1:ncol(volcano))
topography$z <- c(volcano)

# point measurements of something at a few locations
set.seed(42)
measurements <- data.frame(x = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = rnorm(30))

ggplot(mapping = aes(x, y)) +
  geom_contour(data = topography, aes(z = z, color = stat(level))) +
  scale_x_continuous(limits = c(25, 75)) +
  # Color scale for topography
  scale_color_viridis_c(option = "D") +
  # geoms below will use another color scale
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(color = thing)) +
  # Color scale applied to geoms added after new_scale_color()
  scale_color_viridis_c(option = "A")

it breaks and gives the following error:
Error in get(as.character(FUN), mode = "function", envir = envir) : object 'guide_none' of mode 'function' was not found

Based on the error, I believe I've tracked down the problem to this line of code. After messing around with some ggplot objects, it looks like these particular scales don't have guides, so the names of the guides are "none", which is still a character, so it proceeds but doesn't find any function guide_none().

I think all you would need to do is change the if statement here to
if (is.character(scale$guide) & !(scale$guide == "none")) { but I'm actually not sure if this would break anything else. If I get a chance, I'll fork and try it out.

Expand to more scales?

Are there any plans to expand the pkg to support more scale types? E.g. more than on linetype scale, size, shape, etc...

Release ggnewscale 0.4.4

Prepare for release:

  • devtools::build_readme()
  • Check current CRAN check results
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md
  • Polish NEWS
  • Review pkgdown reference index for, e.g., missing topics

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version()

`new_scale` modifies the ggplot object

This might be intended behaviour, in which case just close the issue - but it caught me out! I didn't find it mentioned in the docs, but maybe I missed it?
Adding new_scale to a ggplot object modifies that object. In some cases this caused errors for me in later code, because the ggplot object has changed unexpectedly.

Should p + new_scale() change the p object, if it isn't being assigned back to p?

library(ggplot2)
library(ggnewscale)
topography <- expand.grid(x = 1:nrow(volcano), y = 1:ncol(volcano))
topography$z <- c(volcano)

## create two equivalent ggplot objects
p0 <- ggplot(mapping = aes(x, y)) + geom_contour(data = topography, aes(z = z, color = stat(level))) + scale_color_viridis_c(option = "D")
p <- ggplot(mapping = aes(x, y)) + geom_contour(data = topography, aes(z = z, color = stat(level))) + scale_color_viridis_c(option = "D")

all.equal(p, p0)
[1] TRUE
## ok, as expected they are the same

## now add new scale to p, but WITHOUT explicitly assigning back to `p`
p + new_scale_colour()

all.equal(p, p0)
 [1] "Component “layers”: Component 1: Component 3: Names: 1 string mismatch"                                         
 [2] "Component “layers”: Component 1: Component 3: Length mismatch: comparison on first 2 components"                
 [3] "Component “layers”: Component 1: Component 3: Component 1: Names: 1 string mismatch"                            
 [4] "Component “layers”: Component 1: Component 3: Component 2: target, current do not match when deparsed"          
 [5] "Component “layers”: Component 1: Component 6: Names: 1 string mismatch"                                         
 [6] "Component “layers”: Component 1: Component 9: Names: 4 string mismatches"                                       
 [7] "Component “layers”: Component 1: Component 9: Length mismatch: comparison on first 4 components"                
 [8] "Component “layers”: Component 1: Component 9: Component 1: Modes: list, function"                               
 [9] "Component “layers”: Component 1: Component 9: Component 1: names for target but not for current"                
[10] "Component “layers”: Component 1: Component 9: Component 1: Attributes: < Modes: list, NULL >"                   
[11] "Component “layers”: Component 1: Component 9: Component 1: Attributes: < Lengths: 1, 0 >"                       
[12] "Component “layers”: Component 1: Component 9: Component 1: Attributes: < names for target but not for current >"
[13] "Component “layers”: Component 1: Component 9: Component 1: Attributes: < current is not list-like >"            
[14] "Component “layers”: Component 1: Component 9: Component 1: current is not list-like"                            
[15] "Component “layers”: Component 1: Component 9: Component 2: Modes of target, current: function, list"            
[16] "Component “layers”: Component 1: Component 9: Component 2: target, current do not match when deparsed"          
[17] "Component “layers”: Component 1: Component 9: Component 3: Lengths (0, 3) differ (string compare on first 0)"   
[18] "Component “layers”: Component 1: Component 9: Component 4: target is NULL, current is function"    

Legends are not rendered properly except for the last 2 scales

I have been doing plots with a few colour scales. It used to be OK up to v0.4.1. However, after upgrading to v0.4.2, the legend is rendered wrongly. The colours in the legend are wrong, except for the last 2 scales.

I've constructed a minimal example:

library(ggplot2)
library(ggnewscale)

ggplot(mtcars) + aes(mpg, disp) +
    geom_point(aes(colour=factor(cyl)),  size=7) +
    scale_colour_brewer(type='qual') +
  new_scale_colour() +
    geom_point(aes(colour=factor(carb)), size=5) +
    scale_colour_brewer(type='qual') +
  new_scale_colour() +
    geom_point(aes(colour=factor(gear)), size=3) +
    scale_colour_brewer(palette='Set1') +
  new_scale_colour() +
    geom_point(aes(colour=factor(am)),   size=1) +
    scale_colour_brewer(type='qual')

With ggnewscale v0.4.2, this gives:
Figure 1

Note that the legend for factor(cyl) and factor(carb) are all black. They should be coloured!
The expected, correct, behaviour is exhibited by v0.4.1:
Figure 2

Create a release for version 0.0.0.9000

Could you make a release on GitHub for your first version 0.0.0.9000 of ggnewscale? I'm using it in a project and I like to lock down all the versions of the software using conda and I need a tagged release for your package to be able to do that. Thanks!

How to adjust order of legend items with multiple legends

Hi, thanks for the great package! I was wondering how to specify the order of legend items using multiple legends. I have 2 fill scales and I cannot adjust the ordering using guides(fill = guide_legend(order = 1). Is there a way to differentiate between the 2 fill levels?

new_scale_fill doesn't work with

Hello,

Looking at previous issues, I couldn't find the answer.
My code look like this, before adding new_scale_fill():

ggplot(all_data, aes(x=name,y=whole_gene, fill=paste(category,fig_name,colors))) + geom_bar(position=position_dodge(), stat="identity", color="grey15") + facet_grid(.~fig_name,drop = T,scales = "free",space = "free")+ scale_fill_manual(values = colours)+ guides(fill = FALSE)+
and produces:

image

Adding "new_scale_fill(), here:
ggplot(all_data, aes(x=name,y=whole_gene, fill=paste(category,fig_name,colors))) + geom_bar(position=position_dodge(), stat="identity", color="grey15") + facet_grid(.~fig_name,drop = T,scales = "free",space = "free")+ scale_fill_manual(values = colours)+ guides(fill = FALSE)+ new_scale_fill()+ geom_bar(aes(x=name,y=value_per_category,fill=rep(c("black","yellow"),45)),stat="identity",position=position_dodge(), color="grey45")

output:
image

and I don't understand why...

Error: Don't know how to add new_scale_color() to a plot

I am having trouble getting the package to work as expected. When I run the examples or my own plots I get the following message.

Error: Don't know how to add new_scale_color() to a plot

I changed "new_scale_color()" to "new_scale("color")" in the example code and got the following message

Error: Don't know how to add new_scale("color") to a plot
In addition: Warning messages:
1: In get(results[[i]], pos = which(search() == packages[[i]])) :
internal error -3 in R_decompress1
2: In get(results[[i]], pos = which(search() == packages[[i]])) :
internal error -3 in R_decompress1
3: In get(results[[i]], pos = which(search() == packages[[i]])) :
restarting interrupted promise evaluation
4: In get(results[[i]], pos = which(search() == packages[[i]])) :
internal error -3 in R_decompress1
5: In get(results[[i]], pos = which(search() == packages[[i]])) :
restarting interrupted promise evaluation
6: In get(results[[i]], pos = which(search() == packages[[i]])) :
internal error -3 in R_decompress1
7: In mget(objectNames, envir = ns, inherits = TRUE) :
internal error -5 in R_decompress1
8: In mget(objectNames, envir = ns, inherits = TRUE) :
restarting interrupted promise evaluation
9: In mget(objectNames, envir = ns, inherits = TRUE) :
internal error -5 in R_decompress1

Although this message only appeared the first time I ran the code afterwards it reverted to

Error: Don't know how to add new_scale("color") to a plot

I am using R version 3.5.3 and ggplot version 3.1.0.

Let me know if you need any other information

This package is so helpful, Thanks for putting such effort in!

ggplot2 imports when used in a package

I am having an issue when using ggnewscale from within a package. It is pretty difficult to make a reproducible example because it depends on being in my package, which is a new version of the package 'plotdap'. 'plotdap' has its own object, but embedded in that object is a ggplot object, so let's call the 'plotdap' object 'plot' and the ggplot object is then plot$ggplot. I import ggnewscale in my Description, and the line I am trying is:

plot$ggplot <- plot$ggplot + ggnewscale::new_scale_colour()

okay so if do that on a plot where I need to set a new scale I get the following:

> p1 <-  add_tabledap(p,
+                     sardines, 
+                     ~subsample_count
+ )
 Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'guide_colourbar' of mode 'function' was not found 
10.
get(as.character(FUN), mode = "function", envir = envir) 
9.
match.fun(paste("guide_", scale$guide, sep = "")) 
8.
FUN(X[[i]], ...) 
7.
lapply(scales, bump_aes_scale, new_aes = new_aes) 
6.
bump_aes_scales(plot$scales$scales, new_aes = object) 
5.
ggplot_add.new_aes(object, p, objectname) 
4.
ggplot_add(object, p, objectname) 
3.
add_ggplot(e1, e2, e2name) 
2.
`+.gg`(plot$ggplot, ggnewscale::new_scale("colour")) at add_tabledap.R#112
1.
add_tabledap(p, sardines, ~subsample_count) 

Now this is what leaves me mystified. If i now do

library(ggplot2)

and try the exact same command (the command is a 'plotdap' command more complicated than the one line, but that is where it fails) it works. So somehow a reference to something in ggplot2 is not being found. I am stumped on this one. I looked at the bump_aes_scale() function and don't see why that should make a difference. I haven't posted this new version of 'plotdap' yet because I have been experimenting with using 'ggnewscale', but I could post it. I could then give a complete reproducible example. Basically I am trying to overlay a table like example (points) on a grid.

I should add that the first plot 'p' because it uses 'sf' has both a scale_colour_gradientn and a scale_fill_gradientn but with ggplot2::guides(colour = "none").

I mention the late because I was wondering because bump_aes_scale() tests for this if for some reason it is not catching it.

If you have any suggestions would appreciate it.

-Roy

help adding specific contour line

Hello Elio,

This is more ask for help than an issue.
I am attempting to plot sea level pressure (isobars) contour on an spatial area with 2mb spacing and want a specific isobar (1015) plotted as thicker line than the others and wonder if it is possible with other function and/or with ggplot2/geom_contour related function or something from ggnewscale. Below the command I used to plot the isobars. Now any idea on how to add a command for the 1015 isobar?

syn_plot <- ggplot() +
geom_tile(data = synclas_gather_df, aes(x=x, y=y, fill=value)) +
geom_sf(data = map_bg, fill="transparent")+
geom_contour2(data = synclas_gather_df, aes(x=x,y=y,z=value), binwidth = 2, color = "black") +
scale_fill_gradientn(colours = colorRamps::matlab.like2(100), name = "hPa",breaks=0:5) +
scale_colour_gradient(guide = 'none') + facet_wrap(~key, ncol = 4) +
scale_x_continuous(limits = c(-34,29), expand = c(0, 0))+
scale_y_continuous(limits = c(-9,34), expand = c(0,0))+
theme_bw() + theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())

syn_plot + geom_text_contour(data= synclas_gather_df,aes(x,y,z = value), stroke = 0.10,binwidth = 4,size=3)
the data is a data frame with following format:

time lon lat slp
1 1978-12-30 12:00:00 0 40 1015.
2 1978-12-30 12:00:00 2.5 40 1013.
3 1978-12-30 12:00:00 5 40 1012.
4 1978-12-30 12:00:00 7.5 40 1010.
5 1978-12-30 12:00:00 10 40 1007.
6 1978-12-30 12:00:00 12.5 40 1005.
7 1978-12-30 12:00:00 15 40 1004.
8 1978-12-30 12:00:00 17.5 40 1003.
9 1978-12-30 12:00:00 20 40 1002.
10 1978-12-30 12:00:00 22.5 40 1001.

Thank you

`guides` properties before `new_scale` are not preserved

Hello,

thanks for developing such a useful package!
It seems that ggnewscale::scale_new_color overwrites parameters of ggplot2::guides, when they were written before the creation of the new scale. I was able to fix this by using color_new instead of color in function guides after the creation of the new scale. Is this intended behavior? For me, it is a little confusing that former parameters are not preserved.

library(ggnewscale)
library(tidyverse)

packageVersion("ggnewscale")
#> [1] '0.4.5'

data <-
  iris %>%
  head(10) %>%
  mutate(
    color_a = factor(Petal.Length),
    color_b = factor(Petal.Width)
  )

data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  guides(color = guide_legend(ncol = 2, nrow = 2))

data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4))

# first color guide gets overwritten
data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  guides(color = guide_legend(ncol = 2, nrow = 2)) +
  new_scale_color() +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4))

# workarround: do guides after creating a new scale
data %>%
  ggplot(aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(color = color_a)) +
  new_scale_color() +
  geom_point(aes(color = color_b)) +
  guides(color = guide_legend(ncol = 1, nrow = 4)) +
  guides(color_new = guide_legend(ncol = 2, nrow = 2))

Created on 2022-02-15 by the reprex package (v2.0.0)

ggplot2 (3.3.5)

I'm having some problems with using new_scale() with ggplot2 (v 3.3.5). The last version of ggplot I had working well was 3.3.3. Is anyone else having issues with newer versions of ggplot2?

Release ggnewscale 0.4.7

Prepare for release:

  • Check current CRAN check results
  • Polish NEWS
  • devtools::build_readme()
  • urlchecker::url_check()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version()

Legend issues when using `guides(...)`

Hi,

I am trying to use ggnewscale to plot multiple sets of points each with their own color and alpha scales. I run the following code

  
  groups <- unique(fits[, group.by])
  if(is.null(cols)) {
    cols <- setNames(scales::hue_pal()(length(groups)), groups)
  }
  
  p <- ggplot(fits) + 
    facet_wrap(paste0("~",facet.by), scales=facet.scales, ncol = ncol) + 
    scale_x_continuous(expand = c(0,0)) + 
    theme_classic() + 
    theme(strip.background = element_blank(), strip.text = element_blank())
  
  for(g in groups) {
    p <- p + 
      geom_point(aes(x,y, color=X.weights., alpha=X.weights.), fits[fits[,group.by] == g,], inherit.aes = F) + 
      scale_color_gradientn(name = g, colors=colorRampPalette(c("white", cols[[g]]))(10)[-1]) + 
      scale_alpha(name = g, range=c(min.point.alpha,1)) + 
      labs(color=g, alpha=g)  +       
      new_scale("alpha") + 
      new_scale("color")
  }

and get the plot:
image
where as visible the point size and color are in different guides in the legend. By adding guides(color_new=guide_legend(g), alpha_new=guide_legend(g)) after the new_scale("color") in the loop I am able to get a warning:

In names(guides)[to_change] <- paste0(names(guides), "_new") :
  number of items to replace is not a multiple of replacement length

and the following plot:
image

This is almost there but there is a problem: now the legned isn't aligning with the correct set of points. Looking a bit into the code it is probably because the new scales are named X_new and then next time X_new_new and X_new_new_new. Then the line of the guides won't work as hoped.

A possible fix is to change the function to: new_scale("alpha", "some.name") instead of only adding the _new (or leaving it as the default behavior) and then using that name in the guides will probably work

show.legend = FALSE always applies to all layers

Hola hermano! In this code below, I would like to remove certain legends from some layers using show.legend = FALSE. However, when I desative some legends and let one activated all of them are showed in the final plot. I'm sending the data reproduce the problem. Maybe because gom_sf? Btw, perfect package to help to build maps using ggplot. Thanks for the job!

[data.zip](https://github.com/eliocamp/ggnewscale/files/6436150/data.zip)

load(unzip('data.zip'))

library(ggplot2)
library(ggnewscale)
library(ggspatial)
library(raster)
library(sp)

ggplot() +
  geom_raster(data = basemap_terrain_df_proj, aes(x=x, y=y, fill = as.factor(col)), show.legend = FALSE) + # see here
  scale_fill_manual(values = basemap_colors) +
  new_scale_fill() +
  geom_sf(data = sf_imoveis, aes(fill = NUM_AREA), size = .4, show.legend = TRUE) +
  scale_fill_viridis_c('Área (ha)',option = 'E') +
  new_scale_fill() +
  geom_sf(data = sf_comu, aes(fill = nome, color = nome), fill = NA, size = 1,show.legend = TRUE) +
  annotation_scale(location = "br") +
  annotation_north_arrow(location = "tl") +
  labs(color = "Comunidades",caption = "Fonte dos dados: Mapa Base (Google Maps, 2021).",
       x = "Latitude (m)", y = "Longitude (m)") +
  coord_sf(xlim = c(611500,618000),ylim = c(9140000,9147000),datum = 31984, expand = FALSE, crs = 31984) +
  # guides(color = FALSE, size = FALSE) +
  theme_bw()

This is the result:

image

I would like to hide the legend for the geom_raster layer.

new_scale_fill doesn't work with stat_lineribbon

This came up in willgearty/deeptime#2. When the user makes their custom plot, it looks fine and uses the specified brewer fill scale:

library(tidyverse)
library(tidybayes)
library(ggnewscale)

tb <- 
  tibble(time = 0:100) %>%
  group_by_all() %>%
  do(tibble(value = rnorm(100, .$time, 10),
            group = sample(1:4, 100, TRUE)))

gg <- 
    tb %>%
    ggplot() +
    stat_lineribbon(aes(x = time, y = value)) +
    scale_x_reverse() +
    coord_cartesian(xlim = c(0, 100), 
                    ylim = range(tb$value),
                    expand = FALSE) +
    scale_fill_brewer()
gg

image

But just adding new_scale_fill after this removes the custom fill scale:

gg <- gg + ggnewscale::new_scale_fill()
gg

image

Further, when I try to add another plot with a different fill scale, I get an error:

gg + geom_point(dat = data.frame(x = runif(100,0,100), y = runif(100,0,100), fill = sample(1:4, 100, replace = TRUE)), aes(x = x, y = y, fill = fill))
Error: Discrete value supplied to continuous scale

guide_legend(ncol=2)

Hi @eliocamp,
thanks for your package!

I followed this post on SO (https://stackoverflow.com/a/66808609/16642045) and now I'm trying to align the multiple custom legends in two (or more) vertical columns. I tried to add guides(scale_shape_manual=guide_legend(ncol=2)) to the plot but can't get it to work.

Do you have an idea how to solve this issue?
Thanks!

Best,
David

Partial match warning

When I run this:

library(ggplot2)

options(warnPartialMatchDollar = TRUE)
ggplot(mpg, aes(displ, hwy)) + 
  geom_point(aes(colour = factor(year)), size = 5) + 
  scale_colour_brewer("year", type = "qual", palette = 5) +
  ggnewscale::new_scale_colour() + 
  geom_point(aes(colour = cyl == 4), size = 1, fill = NA) + 
  scale_colour_manual("4 cylinder", values = c("grey60", "black"))

I see:

Warning messages:
1: partial match of 'colour' to 'colour_new' 
2: partial match of 'colour' to 'colour_new' 

Can't remove guides

When using new_scale_color(), setting guides(color = "none") or guides(color = F) only removes the new scale color guide, even if I place one guides() line above the new_scale_color() and one below.

Release ggnewscale 0.5.0

Prepare for release:

  • Check current CRAN check results
  • Polish NEWS
  • devtools::build_readme()
  • urlchecker::url_check()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md
  • Review pkgdown reference index for, e.g., missing topics
  • Draft blog post

Submit to CRAN:

  • usethis::use_version('minor')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version()
  • Finish blog post
  • Tweet
  • Add link to blog post in pkgdown news menu

Legend coloring issue when plotting multiple legends for different geom_point layers

Hi @eliocamp,

Many thanks for your time and effort to develop ggnewscale!

Unfortunately, I'm currently having some issues with the correct coloring of my legend when plotting multiple legends for two geom_point layers using color as single aesthetic. Not sure if it's a bug or just some big oversight of myself...

Please see a reprex below to illustrate my issue.
What I'm trying to achieve are two legends with blue, orange and green points, one with filled colored points using geom_point(shape = 19...) and one with open circles using geom_point(shape = 21...) (like in the bottom plot).

Yet, somehow the coloring of my points in the legend get messed up?!

Many thanks for any feedback and help!

library(tidyverse)
library(ggnewscale)

## make example data
set.seed(123)
d <- tibble(
  feature = rep(base::factor(c("feature1","feature2")), 54),
  name = rep(base::factor(c("name1", "name2", "name3")), 36),
  x = runif(108, min = 0.1, max = 100),
  y = runif(108, min = 0.1, max = 100)
  )

## Point scatterplot with two legends
ggplot(data = d, aes(x = x, y = y)) +
  geom_point(shape = 19, data = subset(d, feature == "feature1"), aes(color = name), size = 3, show.legend = TRUE) +
  scale_color_manual(name = "feature1", values = c("blue", "orange", "green")) +
  new_scale_color() + # geoms below will use another color scale
  geom_point(shape = 21, data = subset(d, feature == "feature2"), aes(color = name), size = 3, show.legend = TRUE) +
  scale_color_manual(name = "feature2", values = c("blue", "orange", "green")) +
  geom_abline(linetype = "dashed") +
  xlim(0, 100) + ylim(0, 100) +
  theme_bw()

ggplot(data = d, aes(x = x, y = y)) +
  geom_point(shape = 19, data = subset(d, feature == "feature1"), aes(color = name), size = 3, show.legend = FALSE) +
  scale_color_manual(name = "feature1", values = c("blue", "orange", "green")) +
  new_scale_color() + # geoms below will use another color scale
  geom_point(shape = 21, data = subset(d, feature == "feature2"), aes(color = name), size = 3, show.legend = TRUE) +
  scale_color_manual(name = "feature2", values = c("blue", "orange", "green")) +
  geom_abline(linetype = "dashed") +
  xlim(0, 100) + ylim(0, 100) +
  theme_bw()

Created on 2021-06-07 by the reprex package (v2.0.0)

sessionInfo()
#> R version 4.0.5 (2021-03-31)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Catalina 10.15.7
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  [1] digest_0.6.27      withr_2.4.2        lifecycle_1.0.0    magrittr_2.0.1    
#>  [5] reprex_2.0.0       evaluate_0.14      highr_0.9          stringi_1.6.2     
#>  [9] rlang_0.4.11       cli_2.5.0          rstudioapi_0.13    fs_1.5.0          
#> [13] vctrs_0.3.8        rmarkdown_2.8      tools_4.0.5        stringr_1.4.0.9000
#> [17] glue_1.4.2         xfun_0.23          yaml_2.2.1         compiler_4.0.5    
#> [21] htmltools_0.5.1.1  knitr_1.33

Created on 2021-06-07 by the reprex package (v2.0.0)

Behaviour with annotations

Something for future development?

library(ggplot2)
library(ggnewscale)
topography <- expand.grid(x = 1:nrow(volcano), y = 1:ncol(volcano))
topography$z <- c(volcano)
measurements <- data.frame(x = runif(30, 1, 80), y = runif(30, 1, 60),
                           thing = rnorm(30))
p <- ggplot(mapping = aes(x, y)) + geom_contour(data = topography, aes(z = z, color = stat(level))) +
     scale_color_viridis_c(option = "D") +
     annotate("polygon", x = c(25, 50, 50, 25), y = c(20, 20, 40, 40), fill = NA, col = "red")
p

OK so far, but:

p + new_scale_color()

Seems to break the colour of the annotation, which shouldn't happen.

control order of legends?

I've got two color scales and two legends for them. I can't find a way to reverse the legend order. Essential code:

  geom_sf(data[data$inout == "Procurement", ], mapping = aes(color = match) , shape=3, size=4 ) +
  scale_color_manual(values = c("red", "orange", "blue", "black", "green"),
                     labels = c("1700-2550", "2150-2500", "1800-2150", "2250-3000", "2400-2850"), 
                     name = "Procurement" ) +
  
  new_scale_colour() +
  
  geom_sf(data[data$inout == "Deployment", ], mapping = aes(color = match), shape = 16 , size=3 ) +
  scale_color_manual( values=c("red", "orange", "blue", "black", "green"),
                      labels=c("2200-3400", "2450-3500", "2200-2950", "2450-3700", "2800-3500"), 
                      name = "Deployment" ) +
  
  theme(legend.direction = "vertical",
        legend.box = "horizontal", . . .

The map. Trying to get 'Procurement' first:
To From_PIPO

ggnewscale doesn't work with stat_summary_hex

I think ggnewscale chokes a bit on stat_...()-type geoms.

Code

ggplot(mapping = aes(x, y)) +
    stat_summary_hex(data = measurements, size = 3, aes(z = thing)) +
    scale_fill_viridis_c(option = "A") +
    new_scale_fill() +
    stat_summary_hex(data = measurements, size = 3, aes(z = thing)) +
    scale_fill_viridis_c(option = "D")

Data

library(ggplot2)
library(ggnewscale)
# Equivalent to melt(volcano)
topography <- expand.grid(x = 1:nrow(volcano),
                          y = 1:ncol(volcano))
topography$z <- c(volcano)

# point measurements of something at a few locations
set.seed(42)
measurements <- data.frame(x = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = rnorm(30))

Result

image

Support for plotly

ggplot(mapping = aes(x, y)) +
  geom_contour(data = topography, aes(z = z, color = stat(level))) +
  scale_color_viridis_c(option = "D") +
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(color = thing)) +
  scale_color_viridis_c(option = "A") -> p

  ggplotly(p)

Warning message:
In geom2trace.default(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) :
  geom_NewGeomContour() has yet to be implemented in plotly.
  If you'd like to see this geom implemented,
  Please open an issue with your example code at
  https://github.com/ropensci/plotly/issues

newplot

The problem seems to be that the classic geoms are redefined in geom_New* which makes that automatically they cannot be processed by plotly, I don't know if there is a way to solve it, but it would be interesting to make this package compatible with plotly.

new_scale_*() position matters

Hi,

It seems like new_scale_*() is doing its job properly after some scale_*(). For your README example, if I move geom_point() from where it is to where the following example shows, the new_scale_color() does not work. Is there a way to solve this problem? For example, if I need to wrap the two geom_*s together (in this case, geom_contour() and geom_point()) as one geom_combined() with different color scales, is there a way for me to do that? Thanks.

ggplot(mapping = aes(x, y)) +
  geom_contour(data = topography, aes(z = z, color = stat(level))) +
  geom_point(data = measurements, size = 3, aes(color = thing)) + # moved geom_point to here
  # Color scale for topography
  scale_color_viridis_c(option = "D") +
  # geoms below will use another color scale
  new_scale_color() +
  # Color scale applied to geoms added after new_scale_color()
  scale_color_viridis_c(option = "A")

[BUG] Missed legend: Where is Wally?

Hi,

Thanks for this package which makes it easy to deal with scales.
I think it might be a BUG.

I was trying to do a geom_tile with categorical values on the x and y-axis where each value along the x-axis has its color scale.
A heatmap where each column has a color scale and legend

So, I manipulated mtcars just to test code, and BANG, after the last tile I missed the legend.
Full example is here

Here is the code I did.

library(tidyverse)
library(ggsci)
library(ggnewscale)

mtcars %>%
  rownames_to_column("rnames") %>% 
  as_tibble() %>% 
  mutate_all(as_factor) %>%
  select(rnames, vs, am, gear, carb) %>% 
  gather(key = "key", value = "value", -rnames) -> temp
#> Warning: attributes are not identical across measure variables;
#> they will be dropped

ggplot() + 
  geom_tile(
    data = temp %>% filter(key=="vs") %>% droplevels, 
    aes(key, rnames, fill=value)
  ) + 
  scale_fill_simpsons() + 
  new_scale_fill() + 
  geom_tile(
    data = temp %>% filter(key=="am") %>% droplevels, 
    aes(key, rnames, fill=value)
  ) + 
  scale_fill_rickandmorty() +
  new_scale_fill() + 
  geom_tile(
    data = temp %>% filter(key=="gear") %>% droplevels, 
    aes(key, rnames, fill=value)
  ) + 
  scale_fill_futurama() +
  new_scale_fill() + 
  geom_tile(
    data = temp %>% filter(key=="carb") %>% droplevels, 
    aes(key, rnames, fill=value)
  ) + 
  scale_fill_tron() +
  theme(legend.position="bottom")

Created on 2020-11-30 by the reprex package (v0.3.0)

Thanks in advance.

Release ggnewscale 0.4.8

Prepare for release:

  • git pull
  • Check current CRAN check results
  • Polish NEWS
  • devtools::build_readme()
  • urlchecker::url_check()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md
  • git push

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • git push
  • usethis::use_github_release()
  • usethis::use_dev_version()
  • git push

Release ggnewscale 0.4.6

Prepare for release:

  • Check current CRAN check results
  • Polish NEWS
  • devtools::build_readme()
  • urlchecker::url_check()
  • devtools::check(remote = TRUE, manual = TRUE)
  • devtools::check_win_devel()
  • rhub::check_for_cran()
  • revdepcheck::revdep_check(num_workers = 4)
  • Update cran-comments.md

Submit to CRAN:

  • usethis::use_version('patch')
  • devtools::submit_cran()
  • Approve email

Wait for CRAN...

  • Accepted 🎉
  • usethis::use_github_release()
  • usethis::use_dev_version()

new_scale_color() not working with geom_segment.

Hi Elio,
I'm not sure if this is an error with new_scale_color() or me being an idiot in its use (probably the latter).

When I try and use new_scale_color() and then geom_segment it recolors the previous layer as well.

dummy<-data.frame(x=runif(100, -180, 180), y=rnorm(100), col=rep(1:5,20))
segs<-data.frame(area=c("WPA","EPA","AOA","CIA","EIA","WPA"), xmin=c(-180, -124,-56.9,30.1,115,170.1), xmax=c(-124.8, -57,30,115,170,180), col=c(1,2,3,4,5,1), y=1.1)

library(ggplot2)
library(ggnewscale);library(dplyr)

ggplot(data=dummy, aes(x=x, y=y, col=as.factor(col)))+geom_point()+scale_color_manual(values = c(1,2,3,4,5), name="colors")

ggplot(data=dummy, aes(x=x, y=y, col=as.factor(col)))+geom_point()+scale_color_manual(values = c(1,2,3,4,5), name="colors")+
    new_scale_color()+
    geom_segment(data=segs, aes(x=xmin, y=1.01, xend=xmax, yend=1.01, col=area), inherit.aes = FALSE, lwd=2) +
    scale_color_viridis_d( name = "Area",option="D")

Created on 2019-10-04 by the reprex package (v0.3.0)

error when using geom_raster

Hello,
When I try using new_scale_fill() with geom_raster I get Error: $ operator is invalid for atomic vectors.

Thanks.

ggnewscale doesn't work with more than one call to new_scale()

I'm not sure if this package was designed to work for multiple calls of new_scale(), but at the moment it doesn't seem to. I feel like this has worked in the past, though, so it seems like it may be a regression due to a recent change.

Example:

library(ggplot2)
library(ggnewscale)
# Equivalent to melt(volcano)
topography <- expand.grid(x = 1:nrow(volcano),
                          y = 1:ncol(volcano))
topography$z <- c(volcano)

set.seed(42)
measurements <- data.frame(x1 = runif(30, 1, 80),
                           x2 = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = rnorm(30))

ggplot() +
  geom_contour(data = topography, aes(x = x, y = y, z = z, color = stat(level))) +
  scale_color_viridis_c(option = "D") +
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(x = x1, y = y, color = thing)) +
  scale_color_viridis_c(option = "A") +
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(x = x2, y = y, color = thing))

Results in the error:

Error in eval(parse(text = parent.layer$geom)) : 
  object 'NewGeomContour' not found

It works fine if you get rid of the last two lines.

Add default scales if not present before `new_scale()`

This is a problem:

library(ggplot2)
library(ggnewscale)
topography <- expand.grid(x = 1:nrow(volcano),
                          y = 1:ncol(volcano))
topography$z <- c(volcano)

set.seed(42)
measurements <- data.frame(x = runif(30, 1, 80),
                           y = runif(30, 1, 60),
                           thing = rnorm(30))

ggplot(mapping = aes(x, y)) +
  geom_contour(data = topography, aes(z = z, color = stat(level))) +
  new_scale_color() +
  geom_point(data = measurements, size = 3, aes(color = thing)) +
  scale_color_viridis_c(option = "A")

Created on 2019-06-29 by the reprex package (v0.3.0)

`override.aes` is ignored with `aesthetics = c("fill", "color")` when using `{ggnewscale}`

When using scale_color/fill_*() for only color or fill, everything works as expected:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.2

p1 <- ggplot(mtcars, aes(factor(gear), mpg, color = factor(gear))) + 
  geom_boxplot() + 
  scale_color_brewer(type = "qual",
                     guide = guide_legend(
                       override.aes = list(
                         fill = c("red", "blue", "blue")
                       )))

p1 + ggnewscale::new_scale_color()

But override.aes is ignored with aesthetics = c("fill", "color") when using {ggnewscale}:

p2 <- ggplot(mtcars, aes(factor(gear), mpg, color = factor(gear))) + 
  geom_boxplot() + 
  scale_color_brewer(type = "qual", 
                     aesthetics = c("fill", "color"),
                     guide = guide_legend(
                       override.aes = list(
                         fill = c("red", "blue", "blue")
                       )))
p2

p2 + 
  ggnewscale::new_scale_color() + 
  ggnewscale::new_scale_fill()

Created on 2022-03-25 by the reprex package (v2.0.1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.