如何创建连接点之间没有数据的折线图- R

fnatzsnv  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(122)

我有以下数据:

abc <- tibble(month = c(1, 3, 12),
              amount = c(100, 20, 300))

abc %>% 
    mutate(month = as.factor(month)) %>% 
    ggplot(aes(x = month, y = amount, group = 1)) +
    geom_line()

我想制作一个折线图,在x轴上显示1到12,就像显示每个月一样,y轴是花费的金额,例如,2月将是零,3月将是20。
谢谢你。

332nm8kg

332nm8kg1#

我认为你提到你有超过一年的数据是相当重要的,所以我在表中添加了一列年份,并以更一般的方式使用它。

# modified data including the year
abc <- tibble(month= c(1, 3, 12, 2),
              year = c(rep(2021, 3), 2022),
              amount = c(100, 20, 300, 10))

# all year x month combinations with 0 amount
abc.full <- expand.grid(month = seq_len(12),
                        year = unique(abc$year),
                        amount = 0)

# fill in amount where available
abc.full$amount[match(paste(abc$year, abc$month),
                      paste(abc.full$year, abc.full$month))] <- abc$amount

abc.full %>% 
  mutate(year = factor(year)) %>% 
  ggplot(aes(x = month, y = amount, color = year)) +
  geom_line() + 
  geom_point(data = mutate(abc, year = factor(year))) +
  scale_x_discrete(limits = factor(1:12),
                   labels = factor(1:12))

我不确定你想如何显示多年的数据,所以这是一种可能性。我还决定用点来强调非零的金额。

blpfk2vs

blpfk2vs2#

在回答您的“缺失数据”问题时,您可以用零填充您的数据,因为它们是!= NA

abc <- tibble(month = c(1:12),
              amount = c(100, 0, 0, 20, rep(0, 7), 300))

在回答您的x轴问题时,您可以尝试:

ggplot() +
  geom_line(data = abc, aes(x = month, y = amount, group = 1)) +
  scale_x_discrete(limits = factor(1:12), # assigns months using factor() to make them discrete 
                   labels = factor(1:12), # assigns labels using factor()
                   expand = c(0, 0)) + # removes space at start/end of x-axis
  scale_y_continuous(expand = c(0, 0)) # removes space at start/end of y-axis

相关问题