geom_bar, изменить расстояние между столбцами на основе переменной

У меня есть следующий гистограмма:

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

Столбцы (или метки x) отмечены одинаково.

Я хотел бы найти способ расставить столбцы не одинаково, пытаясь уменьшить пустое пространство между столбцами, которые уже, чем другие

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

Решение

Другие вопросы по тегам