web-dev-qa-db-ja.com

ggplot2で凡例のタイトルを削除するにはどうすればよいですか?

Ggplot2の凡例について質問があります。

2つの農場での2つの異なる色のニンジンの平均長に関する仮想データセットがあるとします。

carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)

単純な棒グラフを作成します。

require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
geom_bar(position="dodge") +
opts(legend.position="top")
p

私の質問は、凡例からタイトル(「タイプ」)を削除する方法はありますか?

ありがとう!

55
susjoh

凡例のタイトルは、スケールの最初のパラメーターとして渡すことで変更できます。例えば:

_ggplot(carrots, aes(y=MeanLength, x=Farm, fill=Type)) + 
  geom_bar(position="dodge") +
  theme(legend.position="top", legend.direction="horizontal") +
  scale_fill_discrete("")
_

これにはショートカットもあります。つまり、labs(fill="")

凡例はチャートの上部にあるため、凡例の方向を変更することもできます。これを行うには、opts(legend.direction="horizontal")を使用します。

enter image description here

49
Andrie

ユーザー「gkcn」が指摘したように、+ theme(legend.title = element_blank())を使用するのが最良のオプションであることがわかりました。

私にとって(03/26/15)以前に提案されたlabs(fill="")scale_fill_discrete("")を使用して1つのタイトルを削除し、別の凡例を追加するだけで、これは役に立ちません。

47
Tom B.

labsを使用できます:

p + labs(fill="")

plot example

29
rcs

私のために働いた唯一の方法はlegend.title = theme_blank()を使用することであり、labs(fill="")およびscale_fill_discrete("")と比較して最も便利なバリアントであると思います。

ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
geom_bar(position="dodge") +
opts(
    legend.position="top",
    legend.direction="horizontal",
    legend.title = theme_blank()
)

追伸 documentation にはさらに便利なオプションがあります。

23

すでに2つの優れたオプションがあるので、scale_fill_manual()を使用した別のオプションがあります。これにより、バーの色を簡単に指定することもできます。

ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) + 
  geom_bar(position="dodge") +
  opts(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))

Ggplot2(バージョン1.0)の最新バージョン(2015年1月現在)を使用している場合、以下が機能するはずです。

ggplot(carrots, aes(y = MeanLength, x = Farm, fill = Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(legend.position="top") +
  scale_fill_manual(name = "", values = c("Orange" = "orange", "Purple" = "purple"))
6
Chase