geom_bar,根据变量更改列之间的距离

时间:2017-07-17 08:26:04

标签: r ggplot2 bar-chart

我有以下条形图:

library(ggplot2)

df<- data.frame(type = c("a","a","a","b","b","b","c","c","c","d","d","d","e","e","e"), 
         percentage = c(0.3,0.3,0.4,0.2,0.1,0.7,0.3,0.3,0.4,0.8,0.1,0.1,0.3,0.05,0.65),
         size = c(4,4,4,1,1,1,0.5,0.5,0.5,1,1,1,1,1,1),
         class = as.factor(c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)))

ggplot(df, aes(x=type, y=percentage, width=size/3)) + 
  geom_bar(aes(fill = class), stat="identity") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.3, size=10.)) + 
  scale_x_discrete(name="type") +
  scale_y_continuous(name="Percentage",labels=scales::percent) +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_fill_discrete(name = "") 

enter image description here

列(或x刻度线)间隔相等。

我想找到一种方法来平衡列不均匀,试图减少比其他列窄的列之间的空白

1 个答案:

答案 0 :(得分:1)

感谢@Axeman 2回答,这是一个很好的解决方案,可以在列之间保持同样的空白区域:

library(ggplot2)

df<- data.frame(type = c("a","a","a","b","b","b","c","c","c","d","d","d","e","e","e"), 
         percentage = c(0.3,0.3,0.4,0.2,0.1,0.7,0.3,0.3,0.4,0.8,0.1,0.1,0.3,0.05,0.65),
         size = c(4,4,4,1,1,1,0.5,0.5,0.5,1,1,1,1,1,1),
         class = as.factor(c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)))

df$summ <- c(0,0,0, na.omit(0.5 * df$size + 0.5 * dplyr::lag(df$size, n=3))) + 
           max(df$size)/5.0
df$summ <- ave(df$summ,df$class,FUN=cumsum)

ggplot(df, aes(x=summ, y=percentage, width=size)) + 
  geom_bar(aes(fill = class), stat="identity") + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.3, size=10.)) + 
  scale_x_continuous(name="type", breaks=unique(df$summ), labels=c("a","b","c","d","e")) +
  scale_y_continuous(name="Percentage",labels=scales::percent) +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_fill_discrete(name = "")

Solution