[英]ggplot2: geom_bar with custom y limits
我想繪制一個帶有ggplot2
以及自定義y限制。
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"
。
使用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值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.