uclahs-cds / package-BoutrosLab-plotting-general

Functions to Create Publication-Quality Plots
https://uclahs-cds.github.io/package-BoutrosLab-plotting-general
12 stars 4 forks source link

Draw text in outer margin #25

Open stefaneng opened 2 years ago

stefaneng commented 2 years ago

It would be nice to be able to draw text outside of the panel as BPG removes points/text outside of the limits. I included a workaround in BPG using multipanel plot to add text in the margin. Base R solution is included as well.

library(BoutrosLab.plotting.general)

(mtcars.scatter <- create.scatterplot(
    mpg ~ wt,
    data = mtcars,
    text.x = 1,
    text.y = c(5, 40),
    text.label = c('Text shows', 'Text does not show'),
    add.text = TRUE
))

image

workaround.text <- create.scatterplot(
    mpg ~ wt,
    data = mtcars,
    # Don't plot anything
    type = 'n',
    xaxis.tck = 0,
    xlab.label = '',
    ylab.label = '',
    ylimits = c(0, 1),
    axes.lwd = 0,
    xaxis.lab = NULL,
    yaxis.lab = NULL,
    # xat = xat,
    text.x = 1,
    text.y = 0.2,
    text.label = 'Text shows',
    add.text = TRUE
)

# Workaround with multipanel plot
create.multipanelplot(
    list(workaround.text, mtcars.scatter),
    layout.width = 1,
    layout.height = 2,
    plot.objects.heights = c(0.4, 1)
)

image

This is easy enough to do in base R with mtext.

plot(mpg ~ wt, data = mtcars)
mtext('Text shows', at = 2, side = 3)

image

Created on 2022-06-10 by the reprex package (v2.0.1)

stefaneng commented 2 years ago

Better workaround:

library(BoutrosLab.plotting.general);

mtcars.scatter <- create.scatterplot(
    mpg ~ wt,
    data = mtcars,
    text.x = 1,
    text.y = c(5, 40),
    top.padding = 5,
    text.label = c('Text shows', 'Text now shows'),
    add.text = TRUE
    );

mtcars.scatter$par.settings$clip <- list(panel = FALSE);
mtcars.scatter;

image