r语言 - 使用 ggplot2 上变量元素作为绘图标签的上标和下标



使用geom_jitter(),我绘制了ab。对于图上的每个点,我想显示一个形式为 $c^(d(_(e($ 的标签,即带有上标 d 和下标 e 的变量 c,其中 c、d 和 e 是与数据中的 a 和 b 关联的相应值。

我尝试将geom_text()bquote(.(c)^d[e])一起使用,但它显示错误:

Don't know how to automatically pick scale for object of type call. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (42): label, x, y

下面,您可以找到我正在使用的代码和数据。

a <- c(1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3)
b <- c(9.75, 19.0, 9.75, 4.02, 3.1, 19.0, 9.27, 17.2, 9.27, 19.0, 7.78, 6.06, 9.75, 
4.02, 3.05, 3.1, 2.59, 2.29, 19.0, 9.27, 3.93, 17.2, 3.05, 15.59, 9.27, 
3.93, 3.05, 19.0, 9.27, 7.47, 17.2, 7.47, 9.27, 5.87, 5.87, 8.82, 19.0, 
7.78, 5.87, 6.06, 5.01, 4.45)
c <- c('(0, 1)', '(1, 0)', '(0, 2)', '(0, 2)', '(0, 2)', '(1, 1)', '(1, 1)', '(1, 1)', 
'(1, 1)', '(2, 0)', '(2, 0)', '(2, 0)', '(0, 3)', '(0, 3)', '(0, 3)', '(0, 3)', 
'(0, 3)', '(0, 3)', '(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', 
'(1, 2)', '(1, 2)', '(1, 2)', '(2, 1)', '(2, 1)', '(2, 1)', '(2, 1)', '(2, 1)', 
'(2, 1)', '(2, 1)', '(2, 1)', '(2, 1)', '(3, 0)', '(3, 0)', '(3, 0)', '(3, 0)', 
'(3, 0)', '(3, 0)')
d <- c('(0, 0)', '(0, 0)', '(0, 0)', '(0, 0)', '(0, 1)', '(0, 0)', '(0, 0)', '(0, 1)', 
'(1, 0)', '(0, 0)', '(0, 0)', '(1, 0)', '(0, 0)', '(0, 0)', '(0, 0)', '(0, 1)', 
'(0, 1)', '(0, 2)', '(0, 0)', '(0, 0)', '(0, 0)', '(0, 1)', '(0, 1)', '(0, 2)', 
'(1, 0)', '(1, 0)', '(1, 1)', '(0, 0)', '(0, 0)', '(0, 0)', '(0, 1)', '(0, 1)', 
'(1, 0)', '(1, 0)', '(1, 1)', '(2, 0)', '(0, 0)', '(0, 0)', '(0, 0)', '(1, 0)', 
'(1, 0)', '(2, 0)')
e <- c('(0, 1)', '(1, 0)', '(0, 1)', '(0, 2)', '(0, 2)', '(1, 0)', '(1, 1)', '(1, 1)', 
'(1, 1)', '(1, 0)', '(2, 0)', '(2, 0)', '(0, 1)', '(0, 2)', '(0, 3)', '(0, 2)', 
'(0, 3)', '(0, 3)', '(1, 0)', '(1, 1)', '(1, 2)', '(1, 1)', '(1, 2)', '(1, 2)', 
'(1, 1)', '(1, 2)', '(1, 2)', '(1, 0)', '(1, 1)', '(2, 1)', '(1, 1)', '(2, 1)', 
'(1, 1)', '(2, 1)', '(2, 1)', '(2, 1)', '(1, 0)', '(2, 0)', '(3, 0)', '(2, 0)', 
'(3, 0)', '(3, 0)')
data <- data.frame(a, b, c, d, e)
library(ggplot2)
c <- ggplot(data, aes(a, b)) + 
geom_jitter(width = 0.2) + 
geom_text(aes(label = bquote(.(c)^.(d)[.(e)])), 
position = position_jitter(width = 0.2, height = 0))

试试这个,

dd <- data.frame(a, b, c, d, e, stringsAsFactors = FALSE)
dd$lab <- apply(dd, 1, function(row) bquote(.(row[1])^.(row[2])[.(row[3])]))
library(ggplot2)
ggplot(dd, aes(a, b)) + 
geom_jitter(width = 0.2) + 
geom_text(aes(label = lab), parse = TRUE,
position = position_jitter(width = 0.2, height = 0))

最新更新