LoginSignup
7
1

More than 5 years have passed since last update.

文字列として変数に格納されている列名をggplotのaes()に入れたい

Posted at

文字列(シングルクウォート または ダブルクウォートで囲まれている)で格納されている変数をggplotのaes()内の列名に指定して作図をしたかったときに躓いたのでメモ。

失敗パターン

> target <- "id_col"  
> ggplot(tmp, aes_(x = target_col, y = ctr)) + #列名が""に囲われている状態で指定
    geom_col() +
    facet_wrap(~group_name) 

Error in aes_(x = target_col, y = ctr) : object 'ctr' not found

以下で解決

as.name()で囲うと""がなくなる。
※aes_ を使用することと、列名をそのまま指定している列も同様の形式(as.name("列名"))にしておくこと

ggplot(tmp, aes_(x = as.name(target_col), y = as.name("ctr"))) +
    geom_col() +
    facet_wrap(~group_name) 

その他の失敗パターン

・aesではなくaes_を使用する必要がある

> ggplot(tmp, aes(x = as.names(target_col), y = ctr)) + 
    geom_col() +
    facet_wrap(~group_name) 
Error in as.names(target_col) : could not find function "as.names"

print(target_col, quote=F) でも文字列の横の""は削除できるが、xに"print(target_col, quote=F)"という1列を指定したと認識されてしまう

> ggplot(tmp, aes(x = print(target_col, quote=F), y = ctr)) + 
    geom_col() +
    facet_wrap(~group_name) 
7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1