Nickerbocker
Nickerbocker

Reputation: 127

Draw a fill (bar?) beneath line-segments using ggplot

I'm hoping there is an easy geom_ that is not geom_polygon to do what I'm trying to do here. I'd like to have "fills" extend down to 0 on the y-axis and split up by the grouping similar to how the line segments are split up by the "device_period" in my group= aesthetic. I'm trying to make something that looks similar to a bar-chart but with x,y data that is grouped in the way shown in the example.

library(tidyverse)

theme_set(theme_bw())

test_df <- tribble(
  ~x, ~y, ~device, ~period,
  2, 3, 1, 1,
  3, 4, 1, 1,
  4, 4, 1, 1,
  6, 4, 1, 2,
  7, 2, 1, 2,
  8, 0, 1, 2,
  4, 3, 2, 1,
  5, 2, 2, 1,
  6, 2, 2, 2,
  7, 1, 2, 2,
  8, 1, 2, 2,
)


test_df %>%
  mutate(device_period = paste(device, period)) %>%
  ggplot(aes(
    x = x,
    y = y,
    shape = as.factor(device),
    color = as.factor(device),
    group = device_period
  )) +
  geom_point() + geom_line()

Example Code Plot

Upvotes: 0

Views: 190

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145765

You're looking for geom_area. I added a fill aesthetic and put the factor() inside mutate to avoid typing it 3 times. I also set the y-axis to start right at 0.

test_df %>%
  mutate(device_period = paste(device, period),
         device = factor(device)) %>%
  ggplot(aes(
    x = x,
    y = y,
    shape = device,
    fill = device,
    color = device,
    group = device_period
  )) +
  geom_point() +
  geom_area(alpha = 0.4, position = "identity") +
  scale_y_continuous(expand = expansion(c(0, 0.05))) +
  theme_bw()

enter image description here

Upvotes: 2

Related Questions