79

ggplot2の凡例の順序を制御する方法を知っている人はいますか?

私が見ることができるものから、順序は、スケール宣言の順序ではなく、実際のスケールラベルに関連して表示されます。スケールタイトルを変更すると、順序が変更されます。これを強調するために、ダイヤモンドデータセットを使用して小さな例を作成しました。一連のプロットにggplot2を使用しようとしていますが、すべてのプロットの右側に1つの変数を表示したいと思います。現在、これは一部でのみ発生しますが、適切なスケールラベルを保持しながら、希望する順序を適用する方法がわかりません。

library(ggplot2)
diamond.data <- diamonds[sample(nrow(diamonds), 1000), ]
plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) +
  geom_point() + opts(legend.position = "top", legend.box = "horizontal")
plot # the legend will appear shape then colour 
plot + labs(colour = "A", shape = "B") # legend will be colour then shape
plot + labs(colour = "Clarity", shape = "Cut") # legend will be shape then colour
4

2 に答える 2

130

0.9.1では、凡例の順序を決定するためのルールは秘密であり、予測できません。現在、0.9.2、githubの開発バージョンでは、凡例の順序を設定するためのパラメーターを使用できます。

次に例を示します。

plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) +
  geom_point() + opts(legend.position = "top")

plot + guides(colour = guide_legend(order = 1), 
              shape = guide_legend(order = 2))

ここに画像の説明を入力してください

plot + guides(colour = guide_legend(order = 2), 
              shape = guide_legend(order = 1))

ここに画像の説明を入力してください

于 2012-07-09T15:14:00.263 に答える
13

凡例の順序は、スケール名の文字数によって決まるように思われます。(はい、私は同意します、それは奇妙に思えます。)

したがって、回避策は、ラベルにスペースを埋め込むことです。

plot + labs(colour = "Clarity", shape = "      Cut")

ここに画像の説明を入力してください


誰かがすぐに適切な解決策を投稿することを心から願っています!

于 2012-07-09T10:34:31.913 に答える