MYa*_*208 2 plot r bar-chart ggplot2 geom-bar
我想绘制一个ggplot2带有自定义y限制的条形图。
Type <- LETTERS[1:5]
Y <- c(99, 99.5, 99.0, 98.8, 98.5)
df <- data.frame(Type, Y)
Run Code Online (Sandbox Code Playgroud)
下面的代码适用于条形图:
library(ggplot2)
ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) +
geom_bar(stat = "identity") +
theme_bw()
Run Code Online (Sandbox Code Playgroud)
但是,我无法设置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()
Run Code Online (Sandbox Code Playgroud)
已编辑
我想这种行为是由于stat = "identity"。
或者,使用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()
Run Code Online (Sandbox Code Playgroud)
给你:
解决方案使用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))
Run Code Online (Sandbox Code Playgroud)
将geom_rect()x 坐标指定为as.numeric(X) -/+ value; ymin坐标为所需下限和ymax实际 Y 值。