ggplot2:具有自定义y限制的geom_bar [英] ggplot2: geom_bar with custom y limits

查看:298
本文介绍了ggplot2:具有自定义y限制的geom_bar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot2绘制条形图以及自定义y限制.

I want to draw a bar chart with ggplot2 along with custom y limits.

Type <- LETTERS[1:5]
Y    <- c(99, 99.5, 99.0, 98.8, 98.5)

df <- data.frame(Type, Y)

以下代码适用于条形图:

The following code works fine for bar chart:

library(ggplot2)
ggplot(data = df, mapping = aes(x = Type, y = Y, fill = Type)) +
  geom_bar(stat = "identity") +
  theme_bw()

但是,我无法设置y限制.请参见下面的代码.

However, I'm not able to set the y limits. See the code below.

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"引起的.

I guess this behavior is due to stat = "identity".

推荐答案

使用geom_rect()而不是geom_bar()的解决方案:

Solution using geom_rect() instead of 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值.

In geom_rect() specify x coordinates as as.numeric(X) -/+ value; ymin coordinates as wanted lower limit and ymax as actual Y values.

这篇关于ggplot2:具有自定义y限制的geom_bar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆