Parse superscript in discrete axis values on geom_bar

依然范特西╮ 提交于 2019-12-24 18:49:29

问题


I'm trying to add a superscript to some x-axis values in order to connect to a footnote that'll be at the bottom of the page. The easy workaround would just be an asterisk instead of ^a but that won't work for my purposes.

I did a lot of searching and while there's plenty of posts about superscripts in axis labels, I couldn't find any about superscripts in axis values. Most of them appeared to centera round adding a gg + labs(x = expression("blah^a")).

I did find this post about parsing superscripts inside a geom_text() but it appears the same doesn't work for a geom_bar().

Here's some test data:

library(ggplot2)

dat <- data.frame(x = c("alpha", "bravo^a"),
                  y = c(10, 8))

ggplot(data = dat) +
  geom_bar(aes(x = x, 
               y = y),
           stat = "identity")

回答1:


You just need to parse the text inside scale_x_discrete

Edit: add geom_text example

library(ggplot2)

dat <- data.frame(x = c("alpha", "bravo^a"),
                  y = c(10, 8))

ggplot(data = dat) +
  geom_bar(aes(x = x, 
               y = y),
           stat = "identity") +
  scale_x_discrete(labels = parse(text = levels(dat$x))) +
  geom_text(aes(x = x, y = y,
                label = x), 
            parse = TRUE, 
            nudge_y = 1,
            size = 5) +
  theme_minimal(base_size = 14)

Created on 2018-08-27 by the reprex package (v0.2.0.9000).



来源:https://stackoverflow.com/questions/52039716/parse-superscript-in-discrete-axis-values-on-geom-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!