Home > database >  Combining geom_text with substitute doesn't work
Combining geom_text with substitute doesn't work

Time:02-16

I have the following dataset

structure(list(X = c(9.8186734, 19.6373468, 29.4560202, 39.2746936, 
49.093367, 58.9120404, 68.7307138, 78.5493872, 88.3680606, 98.186734
), Y = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), radii = c(530.595715856625, 
530.595715856625, 524.270569515141, 520.785212389348, 524.423046929159, 
524.777454042683, 523.089321742221, 522.852371975715, 523.124870390148, 
522.612174462367), slope = c(-21.796356958782, -21.796356958782, 
-21.796356958782, -21.796356958782, -21.796356958782, -21.796356958782, 
-21.796356958782, -21.796356958782, -21.796356958782, -21.796356958782
)), row.names = c(NA, -10L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x7f989f011ce0>, sorted = "Y")

and I am simply trying to print slope as a text to the figure as

str_slope <- c(substitute("Slope = "~sp~mu*"m/s", list(sp = sprintf("%2.1f", dt[!duplicated(slope), slope]))))
d_text <- data.table(x=2000, y=500, label = str_slope)
ggplot(dt, aes(x = X, y=radii))  
  geom_point() 
  geom_smooth(method = "lm", level = 0.9999, se = TRUE) 
  scale_colour_manual(values = getPalette)  
  labs(x = "time (s)", y = expression("radius ["*mu*"m]"), color = "Speed [µm/s]")  
  geom_text(data = d_text, aes(x = x, y = y, label = label)) 
  theme_default(legend.position = "none")

but I get something like this

enter image description here

Why is the text in str_slope not evaluated as an expression? How can I force ggplot to interpret it as an expression, so that the text will look like

CodePudding user response:

For this type of plot annotation, you should use annotate(geom="text"...) rather than geom_text(). For how to generate the expression, you can use the parse=TRUE argument within annotate().

I think we're missing all your plot data, so here's an example with mtcars that incorporates the contents of str_slope in your example.

str_slope <- c(substitute("Slope = "~sp~mu*"m/s", list(sp = sprintf("%2.1f", dt[!duplicated(slope), slope]))))

p <- ggplot(mtcars, aes(x = wt, y = mpg))   geom_point()

p   annotate(
  "text", x=4, y=25,
  label= str_slope, parse=TRUE)

enter image description here

For your information, geom_text() is designed to be used wherein one or more aesthetics are mapped to a data frame. If you have only one line of text you want to appear on the plot, you should use annotate(geom="text"...), which is used when you do not want to map any aesthetics to a data frame.

  • Related