軸スケール関数からggplot2カスタムテキストフォーマットをtheme()で設定されたフォーマット仕様に従うようにするにはどうすればよいですか?

Aug 18 2020

私のようなフォーマットからggplot2軸に科学表記を変更したい3.23e+63.23 × 10^6。ありがたいことに、この質問はここで回答されています:ggplotを使用して軸上の数値のフォーマットを変更するにはどうすればよいですか?

基本的な場合に適しています。ただし、軸ラベルのフォーマットを変更したい場合は機能しません。これは、次の例で示されています。

library(tidyverse)
ggplot(mpg, aes(displ, hwy*10^9)) + geom_point()

#makes the scientific notation using "AeB" explicitly write out Ax10^B
fancy_scientific <- function(l) {
  # turn in to character string in scientific notation
  l <- format(l, scientific = TRUE)
  # quote the part before the exponent to keep all the digits
  l <- gsub("^(.*)e", "'\\1'e", l)
  # turn the 'e+' into plotmath format
  l <- gsub("e", "%*%10^", l)
  # return this as an expression
  parse(text=l)
}


ggplot(mpg, aes(displ, hwy*10^9)) + 
  theme_classic() +
  geom_point() + 
  scale_y_continuous(labels= fancy_scientific)  +
 theme(text = element_text(face = "bold")) 


どちらが得られますか:

問題は、の呼び出しで指定されているように、Y軸のテキストが太字ではないことthemeです。browser内部で何が起こっているかを確認するために使用するとfancy_scientific、クラス「式」のオブジェクトが返されることがわかります。この場合expression('2'%*%10^+01, '3'%*%10^+01, '4'%*%10^+01)、関数はscales::scientific、回避したいが準拠する種類の科学的記数法を強制するために使用できます。私が設定したテーマの仕様に合わせて、文字列のベクトルを直接返します。表示されたY軸に直接レンダリングされるfancy_scientificような文字列のベクトルを返すように変更すると、'2'%*%10^+01

では、問題は、fancy_scientific関数の出力をテーマの仕様に準拠させるにはどうすればよいかということです。

回答

JordanMandel Aug 20 2020 at 02:54

コメントで示唆されているように、これを行う方法はggtextパッケージです。

library(tidyverse)
library(ggtext)
ggplot(mpg, aes(displ, hwy*10^9)) + geom_point()


#makes the scientific notation using "AeB" explicitly write out Ax10^B
fancy_scientific <- function(l) {
  # turn in to character string in scientific notation
  l <- format(l, scientific = TRUE)
  # quote the part before the exponent to keep all the digits
  l <- gsub("^(.*)e", "'\\1'e", l)
  # turn the 'e+' into plotmath format
  l <- gsub("e", "%*%10^", l)
  # return this as an expression
  parse(text=l)
}


ggplot(mpg, aes(displ, hwy*10^9)) + 
  theme_classic() +
  geom_point() + 
  scale_y_continuous(labels= fancy_scientific)  +
  theme(text = element_text(face = "bold"), 
        axis.text.y = element_markdown(face = "bold")) 

ただし、このコードを実行すると、いくつかの問題が発生します。先頭の数字の周りに引用符があります。これは、の単一引用符を削除することで削除できますl <- gsub("^(.*)e", "'\\1'e", l)。テキストの他の部分に設定する必要のあるデフォルトがいくつかあるため、指定するtextとエラーが発生element_markdown()します。したがって、具体的にはaxis.text.yとして設定する必要がありelement_markdownます。これにより、リアルタイムのサインを表示するという問題が残ります。太字の書式を適用する方法についての質問に答えたので、これについてフォローアップの質問をしますが、デフォルトをelement_markdown正しく設定して、textではなく指定するために使用できるようにする方法についても興味がありますaxis.text.y