ggplot2:不同宽度的线范围/条之间的相同间距

时间:2018-04-06 08:59:42

标签: r ggplot2

library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)

# Generate data
df_durations = data.frame(x = as.character(1:100)) %>%
  mutate(linesize = runif(n = n()),
     linesize = linesize / sum(linesize),
     linesize = linesize / min(linesize)) %>%
  mutate(start_x1 = as.Date(sample(as.Date('2018-01-01'):as.Date('2018-04-01'), size = n(), replace = T), origin='1970-01-01'),
     end_x1 = start_x1 + 20 + sample(-5:5, size = n(), replace = T),
     start_x2 = end_x1 + sample(-5:10, size = n(), replace = T),
     end_x2 = start_x2 + 15 + sample(-5:5, size = n(), replace = T),
     start_x3 = end_x2 + sample(-5:10, size = n(), replace = T),
     end_x3 = start_x1 + 30 + sample(-10:10, size = n(), replace = T)) %>%
  arrange(start_x1) %>%
  mutate(x = factor(x, levels = x, ordered = T),
     fontsize = round(runif(n(), 5, 12)),
     colour = sample(c('black', 'red', 'blue'), n(), replace = T),
     location = cumsum(fontsize))

# Pivot data for plotting
df_durations_long = df_durations %>%
  gather(key, value, contains('start'), contains('end')) %>%
  separate(key, c('id', 'activity'), '_') %>%
  spread(id, value)

# Plot
df_durations_long %>%
  ggplot(aes(x=location)) +
  geom_linerange(aes(ymin=start, ymax=end, colour=activity, size=linesize), alpha=.5) +
  scale_y_date(date_labels = '%b-%Y', date_breaks = '2 month') +
  scale_x_continuous(breaks = df_durations$location, labels = df_durations$x) +
  theme(axis.text.y = element_text(colour = df_durations$colour,
                               size = df_durations$fontsize)) +
  coord_flip()

以上代码生成以下图表。 Linerange chart

如您所见,我们有重叠和非重叠的水平条(预期)。 然而,垂直堆叠的条之间也存在重叠(不是预期的)。 我正在寻找的是一种方法,在每个条形之间引入相等的间距,同时保持所有条形的相对宽度不变。

我尝试使用scale_size_identity,但是我没有设法正确地进行格式化。

0 个答案:

没有答案