In ggplot2, can borders of bars be changed on only

2019-02-25 09:25发布

I know, 3D Barcharts are a sin. But i´m asked to do them and as a trade-off i suggested to only make a border with a slightly darker color than the bar´s on the top and the right side of the bar. Like that, the bars would have some kind of "shadow" (urgh) but at least you still would be able to compare them.

Is there any way to do this?

ggplot(diamonds, aes(clarity)) + geom_bar() 

2条回答
Summer. ? 凉城
2楼-- · 2019-02-25 09:51

As you already said - 3D barcharts are "bad". You can't do it directly in ggplot2 but here is a possible workaround for this.

First, make new data frame that contains levels of clarity and corresponding count for each level.

library(plyr)
df2<-ddply(diamonds,.(clarity),nrow) 

Then in ggplot() call use new data frame and clarity as x values and V1 (counts) as y values and add geom_blank() - this will make x axis with levels we need. Then add geom_rect() to produce shading for bars - here xmin and xmax values are made as.numeric() from clarity and constant is added - for xmin constant should be less than half of bars width and xmax constant larger than half of bars width. ymin is 0 and ymax is V1 (counts) plus some constant. Finally add geom_bar(stat="identity") above this shadow to plot actually barplot.

ggplot(df2,aes(clarity,V1)) + geom_blank()+
  geom_rect(aes(xmin=as.numeric(clarity)-0.38,
                xmax=as.numeric(clarity)+.5,
                ymin=0,
                ymax=V1+250),fill="green")+
  geom_bar(width=0.8,stat="identity")

enter image description here

查看更多
萌系小妹纸
3楼-- · 2019-02-25 09:54

Another possibility, using two sets of geom_bar. The first set, the green ones, are made slightly higher and offset to the right. I borrow the data from @Didzis Elferts.

ggplot(data = df2) + 
  geom_bar(aes(x = as.numeric(clarity) + 0.1, y = V1 + 100),
           width = 0.8, fill = "green", stat = "identity") +
  geom_bar(aes(x = as.numeric(clarity), y = V1),
           width = 0.8, stat = "identity") +
  scale_x_continuous(name = "clarity",
                     breaks = as.numeric(df2$clarity),
                     labels = levels(df2$clarity))+
  ylab("count")

enter image description here

查看更多
登录 后发表回答