2017-12-23 30 views
2

ggplot2の棒グラフをカスタムyの制限とともに描画したいとします。ggplot2:カスタムyの制限を持つgeom_bar

Type <- LETTERS[1:5] 
Y <- c(99, 99.5, 99.0, 98.8, 98.5) 

df <- data.frame(Type, Y) 

次のコードでは、棒グラフのために正常に動作します:

library(ggplot2) 
ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) + 
    geom_bar(stat = "identity") + 
    theme_bw() 

はしかし、私は、y制限を設定することはできませんよ。以下のコードを参照してください。

ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) + 
    geom_bar(stat = "identity") + 
    scale_y_continuous(limits = c(90, 100)) + 
    theme_bw() 

ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) + 
    geom_bar(stat = "identity") + 
    ylim(90, 100) + 
    theme_bw() 

編集は

私は、この動作がstat = "identity"によるものであると思います。

+0

これが可能であればgeom_bar'は 'から行く'として私にはわからない0 ' (y軸にブレークを挿入するような) 'y 'に変更します。 'geom_point'をプロットしないのはなぜですか? – PoGibas

+0

あなたのコメントのために@PoGibasに感謝します。はい、 'geom_point'は別の可能性があります。しかし、私はこれらの点が棒を投げることを示したい。思考。便利な答えは@PoGibasです。 – MYaseen208

答えて

3

geom_rect()代わりgeom_bar()を用いて溶液:

# Generate data 
Type <- LETTERS[1:5] 
Y <- c(99, 99.5, 99.0, 98.8, 98.5) 
df <- data.frame(Type, Y) 

# Plot data 
library(ggplot2) 
ggplot() + 
    geom_rect(data = df, 
       aes(xmin = as.numeric(Type) - 0.3, 
        xmax = as.numeric(Type) + 0.3, 
        ymin = 90, ymax = Y, 
        fill = Type)) + 
    scale_x_continuous(label = df$Type, breaks = 1:nrow(df)) 

geom_rect()においては、xは指定as.numeric(X) -/+ valueとして座標。 yminは望ましい下限値として、ymaxは実際のY値として調整されます。

enter image description here

+0

yが90から始まるように四角形の下の空白スペースを削除する手助けをすれば大いに感謝します。ありがとう – MYaseen208

+0

@ MYASEen208あなたは四角形とダニの間のスペースを意味しますか? – PoGibas

+1

はい長方形とxティックの間の余分なスペース。 – MYaseen208

3

coord_cartesianを使用して代替、:

ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) + 
    geom_bar(stat = "identity") + 
    coord_cartesian(ylim = c(90, 100)) + 
    theme_bw() 

はあなたを与える:

enter image description here

+1

このソリューションはより魅力的です。あなたの素敵な答えに感謝@ルークC。 – MYaseen208

+0

これは私が 'coord_cartesian(ylim = range(df $ Y))'で探していたものです。 – MYaseen208

+1

@ MYaseen208 - いいですよ、それはかなり滑らかです。 –

関連する問題