2017-10-06 147 views
1

我正在使用ggplot2來繪製患者BMI的箱形圖,並且我在x軸中遇到了問題。我想包括BMI單位(公斤/平方米),我希望「2」被上標。當我把我的圖是這樣的:使用「表達式」在ggplot2軸文本中創建特殊字符時的文本對齊方式

require(plyr) 
require(ggplot2) 

Weights <- data.frame(SubjectID = 1:500, 
         Weight = rnorm(500, 28, 7)) 
Weights$Cat <- cut(Weights$Weight, breaks = c(0, 18.5, 25, 30, 40, Inf), 
        right = FALSE) 
Weights$BMIcat <- revalue(Weights$Cat, 
          c("[0,18.5)" = "Underweight\n(<18.5 kg/m2)", 
          "[18.5,25)" = "Normal weight\n(18.5 to 24.9\nkg/m2)", 
          "[25,30)" = "Overweight\n(25 to 29.9\nkg/m2)", 
          "[30,40)" = "Obese\n(30 to 39.9\nkg/m2)", 
          "[40,Inf)" = "Severely obese\n(>40 kg/m2)")) 

ggplot(Weights, aes(x = BMIcat, y = Weight)) + 
     geom_boxplot() + 
     xlab("BMI category") + ylab("Weight (kg)") 

graph with pretty axis text

一切看起來都只是美麗的2的不是上標。我試圖用expression,使這項工作,這裏是我想出最好的:

ggplot(Weights, aes(x = Cat, y = Weight)) + 
     geom_boxplot() + 
     scale_x_discrete(breaks=c("[0,18.5)", "[18.5,25)", "[25,30)", 
           "[30,40)", "[40,Inf)"), 
         labels=c(
          expression("Underweight\n(<18.5 kg/m"^2*")"), 
          expression("Normal weight\n(18.5 to 24.9\nkg/m"^2*")"), 
          expression("Overweight\n(25 to 29.9\nkg/m"^2*")"), 
          expression("Obese\n(30 to 39.9\nkg/m"^2*")"), 
          expression("Severely obese\n(>40 kg/m"^2*")"))) + 
     xlab("BMI category") + ylab("Weight (kg)") 

ugly axis text but superscripted

現在,我的2S是上標,但一切看起來很可怕。它看起來好像突然離開了,或者完全對齊了,而不是居中,2有時離m很遠,軸文本與圖形重疊!有什麼建議麼?

回答

1

你可以只使用Unicode標兩種字符從Latin-1 block

Weights$BMIcat <- revalue(Weights$Cat, 
          c("[0,18.5)" = "Underweight\n(<18.5 kg/m²)", 
          "[18.5,25)" = "Normal weight\n(18.5 to 24.9\nkg/m²)", 
          "[25,30)" = "Overweight\n(25 to 29.9\nkg/m²)", 
          "[30,40)" = "Obese\n(30 to 39.9\nkg/m²)", 
          "[40,Inf)" = "Severely obese\n(>40 kg/m²)")) 
ggplot(Weights, aes(x = BMIcat, y = Weight)) + 
     geom_boxplot() + 
     xlab("BMI category") + ylab("Weight (kg)") 

With Unicode superscript