6
6

More than 5 years have passed since last update.

ggplot2 でベースラインから上下に伸びる棒グラフ #rstatsj

Last updated at Posted at 2015-06-12

ggplot2 でベースラインから上下に伸びる棒グラフを描きたい。

そこで、次のようにする。

データの生成
data <- data.frame(x=LETTERS[1:10], y=rnorm(10, mean=0))
head(data)
結果
  x          y
1 A -0.4755912
2 B  0.1196277
3 C  0.1837534
4 D -0.2376496
5 E  0.8864223
6 F  0.9673385
グラフの描画
library(ggplot2)
ggplot(data, aes(x=x, y=y, fill=y > 0)) + 
  geom_bar(stat="identity") +
  theme(legend.position="none")

Rplot.png

ベースラインが 0 のものは簡単にできた。

しかし、私が本当に欲しかったグラフは、ベースラインが 0 ではなかった。
ちょっと工夫して次のようにした。

データの生成
data2 <- data.frame(x=LETTERS[1:10], y=rnorm(10, mean=1))
head(data2)
結果
  x            y
1 A  1.502520219
2 B -0.909011496
3 C  0.005040713
4 D  1.836899722
5 E  3.064928707
6 F  0.854557083
グラフの描画
base <- 1
ggplot(data2, aes(x=x, y=y-base, fill=y > base)) + 
  geom_bar(stat="identity") +
  scale_y_continuous(labels=function(y) y+base) +
  theme(legend.position="none") +
  ylab("y")

Rplot01.png

できた!

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6