在R语言中用LaTeX设置支持分数的绘图图例或标题
To get LaTeX-formatted fractions (like $\frac{1}{3}$ or $-\frac{1}{3}$) in your plot title or legend, we can use R's plotmath syntax (which mimics LaTeX for mathematical expressions) along with the fractions() function from the MASS package to convert numeric values to their fractional string representations. Here's how to modify your function:
Modified Code
mydraw <- function(n, lb = -pi, up = pi) { # Ensure MASS package is available for fraction conversion if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS package is required for fractional formatting. Install it with: install.packages('MASS')") } # Convert numeric n to a human-readable fractional string frac_string <- MASS::fractions(n) # Build a plotmath expression for the fraction if (grepl("/", frac_string)) { # Split numerator and denominator parts <- strsplit(frac_string, "/")[[1]] numerator <- as.integer(parts[1]) denominator <- as.integer(parts[2]) # Handle negative fractions cleanly if (numerator < 0) { math_expr <- bquote(-frac(.(abs(numerator)), .(denominator))) } else { math_expr <- bquote(frac(.(numerator), .(denominator))) } } else { # Integer case: just use the integer value math_expr <- as.integer(frac_string) } # Generate your curve data dat <- data.frame(t = seq(lb, up, by = 0.001)) xhrt <- function(t) cos(t) - cos(n * t) yhrt <- function(t) sin(t) - sin(n * t) dat$y <- yhrt(dat$t) dat$x <- xhrt(dat$t) # Plot with LaTeX-style title plot(dat$x, dat$y, type = "l", xlab = "", ylab = "", main = bquote("Curve for " ~ .(math_expr))) }
Key Details:
- Fraction Conversion:
MASS::fractions()takes a numeric value (like1/3or-1/3) and converts it to a string like"1/3"or"-1/3", which we can parse into numerator and denominator. - Plotmath Expression:
bquote()lets us insert dynamic values into a mathematical expression. Thefrac(num, den)syntax in plotmath renders as a proper vertical fraction, just like LaTeX's\frac{num}{den}. - Negative Fractions: We handle negative signs separately to ensure the minus sign sits neatly in front of the fraction instead of being stuck in the numerator.
Example Usage:
# Integer case mydraw(n = 2) # Positive fraction mydraw(n = 1/3) # Negative fraction mydraw(n = -1/3)
Each plot will have a title with a clean, LaTeX-style representation of n—integers display as whole numbers, and fractions render as proper vertical fractions.
If you prefer to use the fraction as a legend instead of the title, you can adjust the code to add a legend with legend(..., legend = math_expr) instead of using it in main.
内容的提问来源于stack exchange,提问作者Chen Stats Yu

