添加阴影效果ggplot2条(barplot)

时间:2015-03-11 21:33:29

标签: r ggplot2

我试图在情节中显示较差的设计选择。其中一种墨水浪费,如果是酒吧的阴影效果,人们可能会分散注意力。我想让 ggplot2 这样做。虽然我的基本原则是制作第一层半透明的酒吧层,然后向右移动。我可以稍微高一点,但不会略微向右:

dat <- data_frame(
    School =c("Franklin", "Washington", "Jefferson", "Adams", "Madison", "Monroe"),
    sch = seq_along(School),
    count = sort(c(13, 17, 12, 14, 3, 22), TRUE),
    Percent = 100*round(count/sum(count), 2)
)

dat[["School"]] <- factor(dat[["School"]], levels = c("Franklin", 
    "Washington", "Jefferson", "Adams", "Madison", "Monroe"))

ggplot(dat) +
   geom_bar(aes(x = School, weight=Percent + .5), alpha=.1, width = .6) +
   geom_bar(aes(x = School, weight=Percent, fill = School), width = .6) +
   theme_bw()

enter image description here

此尝试发出以下警告,并忽略透明层(这是明智的):

ggplot(dat) +
   geom_bar(aes(x = School + .2, weight=Percent + .5), alpha=.1, width = .6) +
   geom_bar(aes(x = School, weight=Percent, fill = School), width = .6) +
   theme_bw()

## Warning messages:
## 1: In Ops.factor(School, 0.2) : ‘+’ not meaningful for factors
## 2: In Ops.factor(School, 0.2) : ‘+’ not meaningful for factors

3 个答案:

答案 0 :(得分:5)

我想也许这就是你要找的......?

ggplot(dat) +
    geom_bar(aes(x = as.integer(School) + .2, y= Percent - .5),stat = "identity", alpha=.2,width = 0.6) +
    geom_bar(aes(x = as.integer(School), y=Percent, fill = School),stat = "identity",width = 0.6) +
    scale_x_continuous(breaks = 1:6,labels = as.character(dat$School)) +
    theme_bw()

enter image description here

答案 1 :(得分:3)

使用@joran给我的作品(感谢Joran):

ggplot(dat) +
    geom_bar(aes(x = School, y=Percent), fill=NA, color=NA, width = .6, stat = "identity") +
    geom_bar(aes(x = sch + .075, y=Percent + .5), alpha=.3, width = .6, stat = "identity") +
    geom_bar(aes(x = School, y=Percent, fill = School), width = .6, stat = "identity")

关键是:

  1. 在透明图层之前添加另一个与颜色条相同的图层,但不要填充或着色它们(使用NA
  2. 制作该系数的数字版本(在我的情况下,我已经制作了sch,但没有上一步没有工作
  3. 请勿使用weight,而是使用y&amp; stat = "identity"
  4. enter image description here

答案 2 :(得分:3)

哦有人已经回答了这个问题,但无论如何这里都是我的。由于您只是在这里绘制图片,因此可以使用geom_rect:

xwidth <- 0.5
xoffset <- 0.05
yoffset <- 0.05

my_dat <- data.frame(x=1:5, y=5:1, labels=letters[1:5])

ggplot(my_dat) +
  geom_rect(aes(xmin=x+xoffset, xmax=x+xwidth+xoffset, 
                ymin=0, ymax=y+yoffset), 
            fill='grey', alpha=0.8) +

  geom_rect(aes(xmin=x, xmax=x+xwidth, 
                ymin=0, ymax=y, fill=labels)) +

  scale_x_discrete(labels=my_dat$labels, breaks=my_dat$x) +
  theme_bw()

enter image description here