我在創建結合斜體字母和變數輸入的軸刻度標簽時遇到問題。簡單的說,我想呼叫變數,在每個標簽下面插入n =1等文字。
這是一個示例,除了斜體n 之外的所有內容:
require(ggplot2)
mpg$class <- as.factor(mpg$class)
counts <- rep(1:7, 1)
ggplot(mpg, aes(class, hwy))
geom_boxplot()
scale_x_discrete(labels = paste(levels(mpg$class), "\nn = ", counts, sep = ""))

我的第一個想法是將 Unicode 用于斜體 N,就像我過去對上標數字所做的那樣。但是由于某種原因,這封信太小了,而且在風格上與文本的其余部分不匹配。更重要的是,在我的實際用例中,斜體 n 的所有 Unicode 字符似乎都呈現不對齊,在正常和下標之間的某個地方被壓低。
ggplot(mpg, aes(class, hwy))
geom_boxplot()
scale_x_discrete(labels = paste(levels(mpg$class), "\n\U1D45B = ", counts, sep = ""))

So, I found the plotmath function ~italic(x) could be used to italicize letters. However, there's a clear and unexpected failure when I incorporate it in the paste() line for the x-axis tick labels. Note that the function does work in xlab()
ggplot(mpg, aes(class, hwy))
geom_boxplot() xlab(~italic("n"))
scale_x_discrete(labels = paste(levels(mpg$class), "\n", ~italic("n"), " = ", counts, sep = ""))

I have searched StackOverflow for similar cases. However, none of them need to call for variables:
Add greek letters to axis tick labels in R
Changing one character in axis tick labels to italic while keeping multiple lines
How to change into italic style one letter in R plot without adding a space
How to italicize part (one or two words) of an axis title
I have tried understanding how to use expression() and bquote() while being able to call variables, but I have been unable to produce anything functional.
At this point, any help is very appreciated!
uj5u.com熱心網友回復:
這些天,您可以使用 ggtext 包通過一些 markdown/html 裝飾來設定文本樣式。
library(ggplot2)
library(ggtext)
#> Warning: package 'ggtext' was built under R version 4.1.1
mpg$class <- as.factor(mpg$class)
counts <- rep(1:7, 1)
ggplot(mpg, aes(class, hwy))
geom_boxplot()
scale_x_discrete(
labels = paste0(levels(mpg$class), "<br><i>n = ", counts, "</i>")
)
theme(axis.text.x = element_markdown())

由reprex 包( v2.0.0 )于 2021 年 10 月 16 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/319260.html
上一篇:使用ggplot2繪制雙向條形圖
下一篇:兩個時間序列之間的顏色區域
