0

I have a simple plot of same data from an experiment.

plot(x=sample95$PositionA, y=sample95$AbsA, xlab=expression(position (mm)), ylab=expression(A[260]), type='l')

enter image description here I would like to shade a particular area under the line, let's say from 35-45mm. From what I've searched so far, I think I need to use the polygon function, but I'm unsure how to assign vertices from a big dataset like this. Every example I've seen so far uses a normal curve.

Any help is appreciated, I am very new to R/RStudio!

zx8754
  • 52,746
  • 12
  • 114
  • 209
agentboba
  • 11
  • 1
  • Please provide example data. – zx8754 Feb 15 '18 at 21:07
  • 1
    [This post](https://stackoverflow.com/questions/3494593/shading-a-kernel-density-plot-between-two-points) didn't help? – zx8754 Feb 15 '18 at 21:10
  • have a look to provide example data and write good question https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – MKR Feb 15 '18 at 21:31

1 Answers1

0

Here is a solution using tidyverse tools including ggplot2. I use the built in airquality dataset as an example.

This first part is just to put the data in a format that we can plot by combining the month and the day into a single date. You can just substitute date for PositionA in your data.

library(tidyverse)
df <- airquality %>%
  as_tibble() %>%
  magrittr::set_colnames(str_to_lower(colnames(.))) %>%
  mutate(date = as.Date(str_c("1973-", month, "-", day)))

This is the plot code. In ggplot2, we start with the function ggplot() and add geom functions to it with + to create the plot in layers.

The first function, geom_line, joins up all observations in the order that they appear based on the x variable, so it makes the line that we see. Each geom needs a particular mapping to an aesthetic, so here we want date on the x axis and temp on the y axis, so we write aes(x = date, y = temp).

The second function, geom_ribbon, is designed to plot bands at particular x values between a ymax and a ymin. This lets us shade the area underneath the line by choosing a constant ymin = 55 (a value lower than the minimum temperature) and setting ymax = temp.

We shade a specific part of the chart by specifying the data argument. Normally geom functions act on the dataset inherited from ggplot(), but you can override them by specifying individually. Here we use filter to only plot the points where the date is in June in geom_ribbon.

ggplot(df) +
  geom_line(aes(x = date, y = temp)) +
  geom_ribbon(
    data = filter(df, date < as.Date("1973-07-01") & date > as.Date("1973-06-01")),
    mapping = aes(x = date, ymax = temp, ymin = 55)
    )

This gives the chart below:

Created on 2018-02-20 by the reprex package (v0.2.0).

Calum You
  • 14,687
  • 4
  • 23
  • 42