ggplot2:具有自定义y限制的geom_bar

问题描述 投票:2回答:2

我想用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"

r plot ggplot2 bar-chart geom-bar
2个回答
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


5
投票

替代方案,使用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

© www.soinside.com 2019 - 2024. All rights reserved.