Skip to content

direct labels #427

@grantmcdermott

Description

@grantmcdermott

I needed this for a plot at work yesterday.

Not sure if we want to roll this into an explicit type (and I'm time constrained ATM regardless), but we could at least add it to the tips and tricks vignette. (Caveat: I don't think the RHS margin bump will work with themes.)

library(tinyplot)
palette("classic")

aq = airquality
aq$Month = factor(month.name[aq$Month], levels = month.name[5:9])

# for labels: subset to final dates for each month 
aq2 = aq[aq$Day == ave(aq$Day, aq$Month, FUN = max), ]

plt(
    Temp ~ Day | Month, data = aq,
    type = "l", legend = FALSE, axes = 'l', grid = TRUE
)
text(
    Temp ~ Day, data = aq2, labels = Month,
    pos = 4, offset = 0.2,
    xpd = NA, col = as.integer(Month)
)

The above is okay for shorter labels, but cuts off longer labels. We can bump the RHS margin to fix:

# bump rhs margin for longer labels
omar = par('mar')
omar[4] = omar[4] + max(strwidth(as.character(aq2$Month)))/2
op = par(mar = omar)

plt(
    Temp ~ Day | Month, data = aq,
    type = "l", legend = FALSE, axes = 'l', grid = TRUE
)
text(
    Temp ~ Day, data = aq2, labels = Month,
    pos = 4, offset = 0.2,
    xpd = NA, col = as.integer(Month)
)

par(op)

Created on 2025-06-17 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions