簡體   English   中英

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

[英]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"

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

給你:

在此輸入圖像描述

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM