在图表中展示因子水平与上标文本。

huangapple go评论68阅读模式
英文:

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 &lt;- 20

df &lt;- data.frame(grp = sample(c(&quot;A^1&quot;, &quot;B^3&quot;, &quot;C&quot;), size = size, replace = TRUE),
                 value = rnorm(size, mean = 10, sd = 1)) %&gt;%
  mutate(grp = as.factor(grp)) %&gt;%
  group_by(grp) %&gt;%
  summarise(mean = mean(value, na.rm=TRUE)) %&gt;%
  ungroup()

# barplot
df %&gt;%
  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(&#39;ggtext&#39;)

df %&gt;%
  ggplot(aes(x = grp, y = mean)) +
  geom_col() +
  theme(axis.text.x = ggtext::element_markdown())

在图表中展示因子水平与上标文本。

答案2

得分: 1

你可以使用expression手动指定标签:

xlabels &lt;- c(&quot;A^1&quot; = expression(&quot;A&quot;^1), &quot;B^3&quot; = expression(&quot;B&quot;^3), &quot;C&quot; = &quot;C&quot;)

# 柱状图
df %&gt;% 
  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 &lt;- c(&quot;A^1&quot; = expression(&quot;A&quot;^1), &quot;B^3&quot; = expression(&quot;B&quot;^3), &quot;C&quot; = &quot;C&quot;)

# barplot
df %&gt;%
  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

huangapple
  • 本文由 发表于 2023年5月15日 15:47:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定