2012-07-25 49 views
24

バーの中のパーセンテージで黒で囲まれた棒グラフを作成したいと思います。これはqplotから可能ですか?パーセンテージは表示されますが、特定のバーと揃っていません。ggplot棒グラフにラベルを追加する

パッケージ:ggplot2、これはあなたがggplotの賛成で、離れqplotを使用してから移動を開始するための良い機会となり

created in Illustrator

x <- data.frame(filename = c("file1", "file2", "file3", "file4"), 
        low = c(-.05,.06,.07,-.14), 
        hi = c(.87,.98,.56,.79)) 
x$tot <- x$hi + x$low 

x <- melt(x, id = 'filename') 

bar <- qplot(x = factor(filename), 
      y = value*100, 
      fill = factor(variable), 
      data = x, 
      geom = 'bar', 
      position = 'dodge') + coord_flip() 
bar <- bar + scale_fill_manual(name = '', 
           labels = c('low', 
              'Hi', 
              "Tot"), 
           values = c('#40E0D0', 
              '#FF6347', 
              "#C7C7C7")) 
bar <- bar + geom_text(aes(label = value*100))+geom_bar(colour = 'black') 
bar <- bar + opts(panel.background = theme_rect(colour = NA)) 
bar <- bar + opts(legend.justification = 'bottom') 
print(bar) 
+2

ようこそSOに。非基底R関数を使用しているので、コードを再現するために必要なパッケージへの参照を追加してください。 'library(...)' – Andrie

答えて

41

ここに行く:

library(scales) 
ggplot(x, aes(x = filename, fill = variable)) + 
    geom_bar(stat="identity", ymin=0, aes(y=value, ymax=value), position="dodge") + 
    geom_text(aes(x=filename, y=value, ymax=value, label=value, 
       hjust=ifelse(sign(value)>0, 1, 0)), 
      position = position_dodge(width=1)) + 
    scale_y_continuous(labels = percent_format()) + 
    coord_flip() 

enter image description here

+0

geom_text部分をありがとう。あなたはymax変数推論を説明できますか? –

+0

ああ、申し訳ありません - それはおそらく冗長です。私は奇妙な警告でちょっとした戦いをしなければならなかった。それを取り除き、何が起こるかを見てください。 – Andrie

+1

percent_format()に 'library(scales)'が必要であることに注意してください。 – dudusan

4

の形を変えます。これは、長期的にはるかに容易になります、私を信頼してください。ここで

がスタートだ:哲学的な理由から

library(scales) 
ggplot(data = x,aes(x = factor(filename),y = value)) + 
    geom_bar(aes(fill = factor(variable)),colour = "black",position = 'dodge') + 
    coord_flip() + 
    scale_fill_manual(name = '', 
         labels = c('low', 
           'Hi', 
           "Tot"), 
         values = c('#40E0D0', 
           '#FF6347', 
           "#C7C7C7")) + 
    scale_y_continuous(labels = percent_format()) 

、私はあなたに注釈作品を残して...

+0

ありがとう。まだプロットにテキスト/パーセンテージはありません。 percent_format()に 'value'を渡しますか? –

+1

@RwardBound私は知っています。私は意図的にテキストラベルを省略しました。なぜなら、私はバーグラフにそのようにラベルを付けることに哲学的に反対しているからです。 (しかし、もしあなたがラベルを作るのであれば、 'scale_y_continuous'では何も使用しません。) – joran

+1

私は参照してください。あなたは個人的に何を好きですか?そして、私はどのようにテキストを追加しますか?あなたの助けに非常に感謝します。 –

関連する問題