英文:
Plot factor levels with superscript text
问题
# 伪造数据框
size <- 20
df <- data.frame(grp = sample(c("A¹", "B³", "C"), size = size, replace = TRUE),
value = rnorm(size, mean = 10, sd = 1)) %>%
mutate(grp = as.factor(grp)) %>%
group_by(grp) %>%
summarise(mean = mean(value, na.rm=TRUE)) %>%
ungroup()
# 条形图
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col()
英文:
Does anyone know how I can plot factor levels containing text with superscripts? In the example below I would like to have A^1
and B^3
in the x-axis as superscript text (without '^')
# Fake dataframe
size <- 20
df <- data.frame(grp = sample(c("A^1", "B^3", "C"), size = size, replace = TRUE),
value = rnorm(size, mean = 10, sd = 1)) %>%
mutate(grp = as.factor(grp)) %>%
group_by(grp) %>%
summarise(mean = mean(value, na.rm=TRUE)) %>%
ungroup()
# barplot
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col()
答案1
得分: 3
We can use ggtext::element_markdown
# install.packages('ggtext')
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col() +
theme(axis.text.x = ggtext::element_markdown())
英文:
We can use ggtext::element_markdown
# install.packages('ggtext')
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col() +
theme(axis.text.x = ggtext::element_markdown())
答案2
得分: 1
你可以使用expression
手动指定标签:
xlabels <- c("A^1" = expression("A"^1), "B^3" = expression("B"^3), "C" = "C")
# 柱状图
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col() +
scale_x_discrete(labels = xlabels)
查看这个链接:https://statisticsglobe.com/add-subscript-and-superscript-to-plot-in-r
英文:
You can use expression
and specify manually your labels:
xlabels <- c("A^1" = expression("A"^1), "B^3" = expression("B"^3), "C" = "C")
# barplot
df %>%
ggplot(aes(x = grp, y = mean)) +
geom_col() +
scale_x_discrete(labels = xlabels)
Check out this link: https://statisticsglobe.com/add-subscript-and-superscript-to-plot-in-r
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论