2016-09-18 3 views
2

データセットmpgを使用して、都市mpg、ハイウェイmpg、クラスモデルの3方向の関係をプロットすることができます。添付ファイルBoxplot.pngに示されているグラフを出力する次のコードをggplot2を使用して使用します。ボックスプロットの中央値でファセットを並べ替え

ggplot(mpg,aes(cty,hwy))+ 
    aes(color=class)+ 
    geom_boxplot()+ 
    facet_grid(.~class, scales='free')+ 
    theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+ 
    scale_x_continuous('City mpg')+ 
    scale_y_continuous('Highway mpg')+ 
    theme(legend.position="none") 

質問:

  1. 私は、中央値が増加する順に箱ひげ図を表示したいです。どうすればいいのですか?

  2. 各ボックスプロットの中央に中央値を表示できますか?

答えて

-1

多くの場合、class変数は、レベルが必要に応じて並べ替えられます。このように、あなたのファセットグラフはあなたが望むように注文されます。私は、多くの場合、あなたはまた、中央値を表示することができ、そのようなcompact (med = 26)

+1

コード含有答えはもっとこのウェブサイトの任務に合わせてだろう。ハットウェイズH^H^H^H ^ハットトゥー・ソリューションはあまり価値がありません。 –

2
require(ggplot2) 

aggregate(mpg$hwy, by=list(mpg$class), median) 

mpg$class <- factor(mpg$class, levels = c("compact", "midsize", "subcompact", 
              "2seater", "minivan", "suv", "pickup")) 

ggplot(mpg,aes(cty,hwy))+ 
    aes(color=class)+ 
    geom_boxplot()+ 
    facet_grid(.~class, scales='free')+ 
    theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+ 
    scale_x_continuous('City mpg')+ 
    scale_y_continuous('Highway mpg')+ 
    theme(legend.position="none") 

enter image description here

としてclass変数を再定義し、上に中央値を表示するには

。ここでは良い説明/例です:

How to display the median value in a boxplot in ggplot?

例は次のとおりです。

library(plyr) 
library(ggplot2) 

p_meds <- ddply(p, .(TYPE), summarise, med = median(TOTALREV)) 

ggplot(p,aes(x = TYPE, y = TOTALREV)) + 
    geom_boxplot() + 
    geom_text(data = p_meds, aes(x = TYPE, y = med, label = med), 
       size = 3, vjust = -1.5) 
関連する問題