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

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

Plot factor levels with superscript text

问题

  1. # 伪造数据框
  2. size <- 20
  3. df <- data.frame(grp = sample(c("A¹", "B³", "C"), size = size, replace = TRUE),
  4. value = rnorm(size, mean = 10, sd = 1)) %>%
  5. mutate(grp = as.factor(grp)) %>%
  6. group_by(grp) %>%
  7. summarise(mean = mean(value, na.rm=TRUE)) %>%
  8. ungroup()
  9. # 条形图
  10. df %>%
  11. ggplot(aes(x = grp, y = mean)) +
  12. 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 '^')

  1. # Fake dataframe
  2. size &lt;- 20
  3. df &lt;- data.frame(grp = sample(c(&quot;A^1&quot;, &quot;B^3&quot;, &quot;C&quot;), size = size, replace = TRUE),
  4. value = rnorm(size, mean = 10, sd = 1)) %&gt;%
  5. mutate(grp = as.factor(grp)) %&gt;%
  6. group_by(grp) %&gt;%
  7. summarise(mean = mean(value, na.rm=TRUE)) %&gt;%
  8. ungroup()
  9. # barplot
  10. df %&gt;%
  11. ggplot(aes(x = grp, y = mean)) +
  12. geom_col()

答案1

得分: 3

We can use ggtext::element_markdown

  1. # install.packages('ggtext')
  2. df %>%
  3. ggplot(aes(x = grp, y = mean)) +
  4. geom_col() +
  5. theme(axis.text.x = ggtext::element_markdown())

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

英文:

We can use ggtext::element_markdown

  1. # install.packages(&#39;ggtext&#39;)
  2. df %&gt;%
  3. ggplot(aes(x = grp, y = mean)) +
  4. geom_col() +
  5. theme(axis.text.x = ggtext::element_markdown())

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

答案2

得分: 1

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

  1. 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;)
  2. # 柱状图
  3. df %&gt;%
  4. ggplot(aes(x = grp, y = mean)) +
  5. geom_col() +
  6. 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:

  1. 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;)
  2. # barplot
  3. df %&gt;%
  4. ggplot(aes(x = grp, y = mean)) +
  5. geom_col() +
  6. 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:

确定