我正在使用ggplot2来绘制患者BMI的箱线图,我在x轴上遇到了问题。我想把BMI的单位(kg / m2)包括在内,我希望“2”能够上标。当我像这样制作图表时:
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)")
除了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)")
现在,我的2s是上标的,但其他一切看起来都很糟糕。它看起来像是突然离开或者可能是完全对齐而不是居中,2有时真的远离m,轴文本与图形重叠!有什么建议吗?
答案 0 :(得分:2)
您可以使用{1.0}}
中的Unicode上标两个字符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)")