In ggplot2, can borders of bars be changed on only one side? (color, thickness)

被刻印的时光 ゝ 提交于 2019-12-01 20:42:00

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")

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")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!