Tom
Tom

Reputation: 31

R geom_line not plotting as expected

I am using the following code to plot a stacked area graph and I get the expected plot.

P <- ggplot(DATA2, aes(x=bucket,y=volume, group=model, fill=model,label=volume)) +  #ggplot initial parameters
  geom_ribbon(position='fill', aes(ymin=0, ymax=1))

area plot no lines

but then when I add lines which are reading the same data source I get misaligned results towards the right side of the graph

P + geom_line(position='fill',  aes(group=model, ymax=1))

enter area plot with lines

does anyone know why this may be? Both plots are reading the same data source so I can't figure out what the problem is.

Upvotes: 2

Views: 591

Answers (3)

Nathan Webb
Nathan Webb

Reputation: 457

Actually, if all you wanted to do was draw an outline around the areas, then you could do the same using the colour aesthetic.

ggplot(DATA2, aes(x=bucket,y=volume, group=model, fill=model,label=volume)) +
  geom_ribbon(position='fill', aes(ymin=0, ymax=1), colour = "black")

Upvotes: 1

tim_yates
tim_yates

Reputation: 171084

If you switch to using geom_path in place of geom_line, it all seems to work as expected. I don't think the ordering of geom_line is behaving the same as geom_ribbon (and suspect that geom_line -- like geom_area -- assumes a zero base y value)

ggplot(DATA2, aes(x=bucket, y=volume, ymin=0, ymax=1,
                  group=model, fill=model, label=volume)) +
  geom_ribbon(position='fill') +
  geom_path(position='fill')

Should give you

enter image description here

Upvotes: 0

Derek Corcoran
Derek Corcoran

Reputation: 4092

I have an answer, I hope it works for you, it looks good but very different from your original graph:

library(ggplot2)
DATA2 <- read.csv("C:/Users/corcoranbarriosd/Downloads/porsche model volumes.csv", header = TRUE, stringsAsFactors = FALSE)

In my experience you want to have X as a numeric variable and you have it as a string, if that is not the case I can Change that, but this will transform your bucket into a numeric vector:

bucket.list <- strsplit(unlist(DATA2$bucket), "[^0-9]+")

x=numeric()
for (i in 1:length(bucket.list)) {
     x[i] <-  bucket.list[[i]][2]  
     }

DATA2$bucket <- as.numeric(x)

P <- ggplot(DATA2, aes(x=bucket,y=volume, group=model, fill=model,label=volume)) + 
geom_ribbon(aes(ymin=0, ymax=volume))+ geom_line(aes(group=model, ymax=volume))

It gives me the area and the line tracking each other, hope that's what you needed

Upvotes: 0

Related Questions