ggplot2轴文本格式不适用于指数 [英] ggplot2 axis text formatting won't work with exponents

查看:68
本文介绍了ggplot2轴文本格式不适用于指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将ggplot的轴文本更改为某种表达式(在本例中为10 ^ .x)很容易.但是,转换文本后,它将失去粗体格式.

我想知道是否存在一种保留粗体格式但又具有如下所示的指数标签的方法.

 库(ggplot2)xxx<-data.frame(x = c(-5,-4,-3),y = c(1,1,1))ggplot(xxx,aes(x,y))+geom_point()+scale_x_continuous(label = scales :: label_math(expr = 10 ^ .x))+theme_bw(base_size = 20)+主题(axis.text = element_text(face ="bold")) 

由(v0.3.0)创建于2020-08-31

sup>

It is easy enough to change the axis text of a ggplot to some sort of expression (in this case 10^.x). However, when the text is transformed, it loses bold formatting.

I was wondering if there was a way to retain bold formatting but also have the exponent labelling shown below.

library(ggplot2)

xxx <- data.frame(
  x = c(-5, -4, -3),
  y = c(1, 1, 1)
)

ggplot(xxx, aes(x, y)) + 
  geom_point() + 
  scale_x_continuous(label = scales::label_math(expr = 10^.x)) + 
  theme_bw(base_size = 20) + 
  theme(axis.text = element_text(face = "bold"))

Created on 2020-08-31 by the reprex package (v0.3.0)

解决方案

I solved my own problem just after posting this. I adapted the make_labels function from an answer to this question.

The trick is to paste the axis numbers as text and then use bold (or italic or whatever) within an expression to control the formatting.

library(ggplot2)

xxx <- data.frame(
  x = c(-5, -4, -3),
  y = c(1, 1, 1)
)

exp_bold <- function(lab) {
  do.call(
    expression,
    lapply(paste(lab), function(x) bquote(bold("10"^.(x))))
  )
}

ggplot(xxx, aes(x, y)) + 
  geom_point() + 
  scale_x_continuous(label = exp_bold) + 
  theme_bw(base_size = 20) + 
  theme(axis.text = element_text(face = "bold"))

Created on 2020-08-31 by the reprex package (v0.3.0)

这篇关于ggplot2轴文本格式不适用于指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆