0

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

Nickerbocker
  • 117
  • 8

1 Answers1

2

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

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    Are you setting a default theme? Or just simplifying it for SO? That doesn't look like the usual. (It doesn't matter, just curious, perhaps that's `theme_minimal()`?) – r2evans Jan 10 '22 at 17:23
  • 1
    I always do theme_set(theme_bw()) and didn't include it in my example code. – Nickerbocker Jan 10 '22 at 17:24
  • 1
    Thanks for the reminder. A [previous question I worked on](https://stackoverflow.com/questions/70653853/decimal-digits-in-slope-graph-with-ggplot2/70654097#70654097) OP put `theme_set(theme_classic())` in the question. Annoying when users unnecessarily put options changes in their questions. (And @Nickerbocker thanks for not including it in your question.) – Gregor Thomas Jan 10 '22 at 17:25