绘制连续变量离散

时间:2019-04-05 15:23:19

标签: r ggplot2

我有此数据:

samp

date_block_num  sales
            <dbl>  <dbl>
 1              0 131479
 2              1 128090
 3              2 147142
 4              3 107190
 5              4 106970
 6              5 125381
 7              6 116966
 8              7 125291
 9              8 133332
10              9 127541
# ... with 25 more rows

date_block_num代表一个月。我想按时间序列方式绘制日期。

如果我使用此代码,date_block_num将被绘制为连续变量(0、10、20等),但它应该是离散的(1、2、3等)。

  samp %>% 
  ggplot(aes(date_block_num, sales)) +
  geom_line()

enter image description here

如果我使用这个:

  samp %>% 
  ggplot(aes(as.factor(date_block_num), sales)) +
  geom_line()

  samp %>% 
  ggplot(aes(date_block_num, sales)) +
  geom_line(aes(group = date_block num)

我得到:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic? 

任何想法如何解决此问题?

dput(samp) 
structure(list(date_block_num = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 
9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 
25, 26, 27, 28, 29, 30, 31, 32, 33, 34), sales = c(131479, 128090, 
147142, 107190, 106970, 125381, 116966, 125291, 133332, 127541, 
130009, 183342, 116899, 109687, 115297, 96556, 97790, 97429, 
91280, 102721, 99208, 107422, 117845, 168755, 110971, 84198, 
82014, 77827, 72295, 64114, 63187, 66079, 72843, 71056, 0)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -35L))

1 个答案:

答案 0 :(得分:2)

您应该能够使用scale_x_continuous指定x轴标签。

samp %>% 
   ggplot(aes(date_block_num, sales)) +
   geom_line() +
   scale_x_continuous(breaks = samp $date_block_num)