Как отцентрировать линию в ggplot2 :: geom_step (), аналогично highcharter - PullRequest
0 голосов
/ 02 мая 2019

Для моего графика я бы хотел, чтобы выравнивание линии ggplot2::geom_step() было сосредоточено вокруг моих точек, а не выровнено по левому краю

В highcharter::hc_add_series(type = "line") есть опция под названием step = "center". См. Мой jsfiddle для взгляда, на который я иду в ggplot2.

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.1

my_data <- 
  data.frame(
           x = c("2015-06", "2015-07", "2015-08", "2015-09",
                 "2015-10", "2015-11", "2015-12", "2016"),
           y = c(35, 41, 40, 45, 56, 54, 60, 57),
          cl = c(37, 37, 37, 37, 59, 59, 59, 59),
         ucl = c(48, 47, 47, 47, 69, 69, 68, 68),
         lcl = c(26, 27, 27, 27, 48, 49, 49, 49)
  )

# Minimal ggplot
ggplot(my_data, aes(x = x, y = y, group = 1)) +
  geom_line() + 
  geom_point() + 
  geom_step(aes(y = cl), linetype = "dashed") +
  geom_step(aes(y = ucl), linetype = "dotted") +
  geom_step(aes(y = lcl), linetype = "dotted")

Создано в 2019-05-02 пакетом представ. (v0.2.1)

1 Ответ

1 голос
/ 03 мая 2019

Вы можете использовать position = position_nudge(x = -0.5)

Я скорректировал значения lcl и ucl, чтобы сделать изменения более понятными.

my_data <- 
  data.frame(
    x = as.Date(c("2015-06-01", "2015-07-01", "2015-08-01", "2015-09-01",
          "2015-10-01", "2015-11-01", "2015-12-01", "2016-01-01")),
    y = c(35, 41, 40, 45, 56, 54, 60, 57),
    cl = c(37, 37, 37, 37, 59, 59, 59, 59),
    ucl = c(48, 47, 42, 47, 70, 69, 68, 68),
    lcl = c(26, 27, 30, 27, 48, 49, 50, 49)
  ) 

ggplot(my_data, aes(x = x, y = y, group = 1)) +
  geom_line() + 
  geom_point() + 
  geom_step(aes(y = cl), position = position_nudge(x = -15)) +
  geom_step(aes(y = ucl), position = position_nudge(x = -15)) +
  geom_step(aes(y = lcl), position = position_nudge(x = -15))

enter image description here

...