LoginSignup
5
5

More than 5 years have passed since last update.

legendやfacet_*のラベルの表示を変えたい

Posted at

Q.

legendのラベル(図中のAの部分)やfacet_*のラベル(図中のBの部分)を短く変えたいのですが、どうすればよいでしょうか?

example.R
library(ggplot2)

ggplot(data=iris, aes(x=Petal.Length, fill=Species)) + geom_histogram(alpha=0.4, position="identity")
ggplot(data=iris, aes(x=Petal.Length)) + geom_histogram(position="identity") + facet_grid(Species ~ .)

example.png

A.

levels関数を使ってfactorのlevelの名前(level attribute)を変えます。

OK_example.R
library(ggplot2)

levels(iris$Species)
# [1] "setosa"     "versicolor" "virginica"
levels(iris$Species) <- c("S", "Ve", "Vi")

ggplot(data=iris, aes(x=Petal.Length, fill=Species)) + geom_histogram(alpha=0.4, position="identity")
ggplot(data=iris, aes(x=Petal.Length)) + geom_histogram(position="identity") + facet_grid(Species ~ .)

levels(x)では今のlevel attributeが取得されます。このlevelの順序は保持したまま、表示名を変えるにはlevels(x) <- valueを使います。詳しくはlevels関数のヘルプをみてください。結果は以下になります。
OK.png
ちなみに表示名ではなくて表示順序を変えたい時は「x軸を並べ替えたい」を参考にしてください。

参考資料

5
5
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
5
5