简体   繁体   中英

Missing line segments in line plot by groups in ggplot in R

I have created a line plot by groups for a cumulative sum in R using ggplot. My problem is that some of the lines contain missing segments -- either at the beginning of a line, end of a line, or in the middle of a line. How do I fix this?

问题

library(dplyr)
library(ggplot2)

df.1 <-
  data.frame(
    x = c(1, 2, 3, 4),
    y = c(10, 23, 25, 28),
    z = factor(1)
  )

df.2 <-
  data.frame(
    x = c(3, 4, 5, 6),
    y = c(5, 10, 12, 16),
    z = factor(2)
  )

df.3 <-
  data.frame(
    x = c(1, 3, 5, 6),
    y = c(2, 7, 8, 12),
    z = factor(3)
  )

df <-
  df.1 %>%
    full_join(
      df.2
    ) %>%
    full_join(
      df.3
    )

df

plot <-
  ggplot(
    df
  ) +
  aes(
    x = x,
    y = y,
    color = z
  ) +
  geom_point() +
  geom_line() +
  theme_minimal()

plot

You can use base::expand.grid and zoo::fill to fix this.

解决方案

df.shell <-
  expand.grid(
    unique(df$z),
    unique(df$x)
  )
names(df.shell) <- c("z", "x")

df.shell

df.full <-
  df.shell %>%
  left_join(df, by = c("z", "x")) %>%
  arrange(z, x)

df.full

df.full.filled <-
  df.full %>%
  group_by(z) %>%
  mutate(y = ifelse(x == 1 & is.na(y), 0, y)) %>%
  fill(y, .direction = "updown")

df.full.filled

plot.filled <-
  ggplot(
    df.full.filled
  ) +
  aes(
    x = x,
    y = y,
    color = z
  ) +
  geom_point() +
  geom_line() +
  theme_minimal()

plot.filled

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM