[R]Play with ggplot2 Part 03 “Positive/Negative BarPlot”

“CHART OF THE DAY” をみていたら、 Positive/Negative Value をとり、正負によって色を分ける棒グラフが利用されていた。

同じようなグラフを ggplot2 で実現してみた。

Program

library(ggplot2)
df <- data.frame(
     country = c('Philippines', 'Thailand', 'Peru', 'Chile', 'Malaysia', 'Hungary', 'Portugal', 'Italy', 'Spain', 'Greece'),
     total_return  = c(58.11, 55.79, 54.65, 49.72, 38.32, -11.03, -11.48, -13.71, -20.31, -41.96))
df$color <- ifelse(df$total_return >= 0, 'black', 'red')
df <- transform(df, country = reorder(country, total_return)) 

> df
       country total_return color
1  Philippines        58.11 black
2     Thailand        55.79 black
3         Peru        54.65 black
4        Chile        49.72 black
5     Malaysia        38.32 black
6      Hungary       -11.03   red
7     Portugal       -11.48   red
8        Italy       -13.71   red
9        Spain       -20.31   red
10      Greece       -41.96   red

p <- ggplot(df, aes(country, total_return, fill=color))
p <- p + geom_bar() + coord_flip() +
     opts(title="Best And Worst Performing Stock Markets Of 2010", legend.position="none") +
     geom_text(aes(label=country, y=-3),  hjust = 1) +
     scale_fill_manual(values = c("black" = "black", "red" = "red"))

# add copyright
caption <- 'Source : DailyFinance'
p <- p + geom_text(aes(label = caption),
                   data=data.frame(total_return = 45, country='Greece',  color='black'), size=5)
p

MEMO

  • ifelse で正負の色分けをするあたりは Learning R を参考にさせてもらった。
  • 棒グラフを指定した色で fill する方法がよくわからず、最後は強引に scale_fill_manual を利用した。

—–
Pure R Implementation

コメント投稿してもらった、標準Rライブラリによるプロット

Advertisements
Tagged with: , , ,
Posted in R
2 comments on “[R]Play with ggplot2 Part 03 “Positive/Negative BarPlot”
  1. foo says:

    barplot(rev(df$total_return), offset=0, horiz=TRUE, names.arg=rev(df$country), las=1, col=rev(df$color))
    text(0, (1:nrow(df))*1.2-0.6, rev(df$country), pos=2)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: