ggplot2:geom_bar 具有自定义 y 限制
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 值。
备选方案,使用 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()
给你:
我想绘制带有 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 值。
备选方案,使用 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()
给你: