user2034412
user2034412

Reputation: 4282

Set the width of ggplot geom_path based on a variable

I have two functions, a and b, that each take a value of x from 1-3 and produce an estimate and an error.

x    variable    estimate   error
1    a           8          4
1    b           10         2
2    a           9          3
2    b           10         1
3    a           8          5
3    b           11         3

I'd like to use geom_path() in ggplot to plot the estimates and errors for each function as x increases.

So if this is the data:

d = data.frame(x=c(1,1,2,2,3,3),variable=rep(c('a','b'),3),estimate=c(8,10,9,10,8,11),error=c(4,2,3,1,5,3))

Then the output that I'd like is something like the output of:

ggplot(d,aes(x,estimate,color=variable)) + geom_path()

but with the thickness of the line at each point equal to the size of the error. I might need to use something like geom_polygon(), but I haven't been able to find a good way to do this without calculating a series of coordinates manually.

If there's a better way to visualize this data (y value with confidence intervals at discrete x values), that would be great. I don't want to use a bar graph because I actually have more than two functions and it's hard to track the changing estimate/error of any specific function with a large group of bars at each x value.

Upvotes: 1

Views: 2964

Answers (2)

user2034412
user2034412

Reputation: 4282

I found geom_ribbon(). The answer is something like this:

ggplot(d,aes(x,estimate,ymin=estimate-error,ymax=estimate+error,fill=variable)) + geom_ribbon()

Upvotes: 0

rawr
rawr

Reputation: 20811

The short answer is that you need to map size to error so that the size of the geometric object will vary depending on the value, error in this case. There are many ways to do what you want like you have suggested.

df = data.frame(x = c(1,1,2,2,3,3),
                variable = rep(c('a','b'), 3), 
                estimate = c(8,10,9,10,8,11), 
                error = c(4,2,3,1,5,3))

library(ggplot2)
ggplot(df, aes(x, estimate, colour = variable, group = variable, size = error)) + 
  geom_point() + theme(legend.position = 'none') + geom_line(size = .5)

Upvotes: 1

Related Questions