簡體   English   中英

如何在 ggplot 的自動注釋中使用變量值作為下標文本

[英]How to use a value of a variable as subscripted text in an automated annotation to ggplot

我想在我的 geom_density_ridges() plot 中添加一個注釋,它指示 scale_x_continous() 的定義限制

在下面的示例中,有一些數據可以構建 plot。名為grob1的注釋導致我想要實現取消變量limit_quantile的值的那種注釋。 (這些圖稍后將在應用系列函數之一的調用中繪制,其中我的原始數據集的不同變量需要不同的 plot 參數,以提高批次的可讀性。)

有沒有辦法使用變量limit_quantile的值甚至可以使用來自as.character(limit_quantile)的輔助變量作為文本輸入? 或者是否有其他方法可以在注釋中自動友好地創建下標文本?

## I like to add a subscript text from a variable value
# 2022-DEC-02


df1 <- data.frame(v1 = c(1:100), class = 1, v2 = rnorm(100) )
df2 <- data.frame(v1 = c(1:100), class = 2, v2 = rnorm(100)*5+10 )
df3 <- data.frame(v1 = c(1:100), class = 3, v2 = rnorm(100)*10+25 )

df <- rbind(df1,df2,df3)


limit_quantile <- 0.99

ridge_plot <- ggplot(df, aes(x = v2, y = as.factor(class), group = as.factor(class))) + 
    geom_density_ridges(stat = "binline", rel_min_height = 0.005 , binwidth = 1,  alpha = 0.5,scale = 0.99) +
    scale_y_discrete(expand = c(0.01, 0), breaks = c(1:3)) +
    scale_x_continuous(expand = c(0.01, 0), limits = quantile(df$v2, c(0, limit_quantile))) +
    theme_ridges() +
    #ylab("Relative Häufigkeit je Teilbauflächenklasse") +
    xlab("Values of v2") +
    ylab(NULL) +
    theme(axis.title.x = element_text(hjust = 0.5))


grob1 <- grobTree(textGrob(bquote("X-Axis-Limit: Q"[0.95]), x=0.9,  y=0.1, hjust=1,
                           gp=gpar(fontsize = 10.5, fontface="italic")))

ridge_plot_text1 <- ridge_plot  + annotation_custom(grob1)
ridge_plot_text1

grob2 <- grobTree(textGrob(bquote("X-Axis-Limit: Q"[limit_quantile]), x=0.9,  y=0.1, hjust=1,
                           gp=gpar(fontsize = 10.5, fontface="italic")))
ridge_plot_text2 <- ridge_plot  + annotation_custom(grob2)
ridge_plot_text2

# Credits for annotation: http://www.sthda.com/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software
# Credits for bquote():   https://www.geeksforgeeks.org/superscript-and-subscript-axis-labels-in-ggplot2-in-r/

我試圖將值作為字符傳遞給 bquote(): limit_quantile_text <- as.character(limit_quantile) ,但是如果 bquote() 和 textGrob() 並沒有改變行為


 grobTree(textGrob(bquote("X-Axis-Limit: Q"[limit_quantile_text ]), x=0.9,  y=0.1, hjust=1,
                           gp=gpar(fontsize = 10.5, fontface="italic")))

此外,我嘗試使用 get(),它在定義 aes() 元素時起作用

#second try
grob2 <- grobTree(textGrob(bquote("X-Axis-Limit: Q"[get(limit_quantile)]), x=0.9,  y=0.1, hjust=1,
                           gp=gpar(fontsize = 10.5, fontface="italic")))

這里的例子讓我現在清楚了正確的 bquote() 語法。 .()表示法可以使用包含字符值/字符串的變量。 所以對於上面的例子,代碼是:

grob2 <- grobTree(textGrob(bquote("X-Axis-Limit: Q"[.(limit_quantile)]), x=0.9,
  y=0.1, hjust=1,
 gp=gpar(fontsize = 10.5, fontface="italic")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM