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

时间:2017-12-23 08:42:38

标签: r plot ggplot2 bar-chart geom-bar

我想绘制一个带有GET product,account/producttype,accounttype/_search { "query": { "bool": { "should": [ { "bool": { "should": [ { "match": { "title.keyword": { "boost": 1000, "query": "Bed Room" } } } ], "filter": [ { "term": { "_index": { "value": "product" } } } ] } } ] } } } 的条形图以及自定义y限制。

ggplot2

以下代码适用于条形图:

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

df <- data.frame(Type, Y)

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

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

被修改

我猜这种行为是由于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() 造成的。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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