ggplot annotate标签解析错误:paste拼接后触发unexpected symbol错误
Fixing ggplot Annotation Parse Error for Statistical Labels
The error you’re encountering happens because when parse = TRUE, ggplot expects your label string to follow plotmath syntax (R’s language for mathematical annotations), but your current stat string doesn’t adhere to those rules. Specifically:
- Plotmath uses
==for equality (not plain=), - Plain text like "p-value" needs wrapping in
plain()to avoid being misinterpreted as math symbols, - Use
~to add spacing between elements for readability.
Here’s the corrected code that will render your desired label properly, including the superscript for R²:
# Sample data df <- data.frame(x = rnorm(10), y = rnorm(10)) # Create a plotmath-compatible label string stat <- paste0("R^2 == 0.81 ~ plain('p-value') == 0.04 ~ plain('n') == 50") # Generate the plot with correct annotation ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse = TRUE, label = stat)
How this works:
R^2: Plotmath uses^to create superscripts, so this renders as R².==: Replaces the plain=to signal equality in plotmath syntax.plain('p-value'): Ensures "p-value" and "n" are rendered as regular text instead of being parsed as mathematical expressions.~: Adds a space between each statistical term for clean formatting.
Alternatively, you can pass the expression directly without building a string:
ggplot(df, aes(x = x, y = y)) + geom_point() + annotate("text", x = mean(df$x), y = mean(df$y), parse = TRUE, label = expression(R^2 == 0.81 ~ plain("p-value") == 0.04 ~ plain("n") == 50))
Both approaches will produce your exact desired label: R² = 0.81, p-value = 0.04, n = 50 centered at the mean of your x and y values.
内容的提问来源于stack exchange,提问作者Jen
相关产品推荐
相关产品推荐

