Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading