Trying to add geom_points to an autolayer() line ("fitted" in pic), which is a wrapper part of autoplot() for ggplot2 in Rob Hyndmans forecast package (there's a base autoplot/autolayer in ggplot2 too so same likely applies there).
Problem is (I'm no ggplot2 expert, and autoplot wrapper makes it trickier) the geom_point() applies fine to the main call, but how do I apply similar to the autolayer (fitted values)?
Tried type="b" like normal geom_line() but it's not an object param in autolayer().
require(fpp2)
model.ses <- ets(mdeaths, model="ANN", alpha=0.4)
model.ses.fc <- forecast(model.ses, h=5)
forecast::autoplot(mdeaths) +
forecast::autolayer(model.ses.fc$fitted, series="Fitted") + # cannot set to show points, and type="b" not allowed
geom_point() # this works fine against the main autoplot call
This seems to work:
library(forecast)
library(fpp2)
model.ses <- ets(mdeaths, model="ANN", alpha=0.4)
model.ses.fc <- forecast(model.ses, h=5)
# Pre-compute the fitted layer so we can extract the data out of it with
# layer_data()
fitted_layer <- forecast::autolayer(model.ses.fc$fitted, series="Fitted")
fitted_values <- fitted_layer$layer_data()
plt <- forecast::autoplot(mdeaths) +
fitted_layer +
geom_point() +
geom_point(data = fitted_values, aes(x = timeVal, y = seriesVal))
There might be a way to make forecast::autolayer do what you want directly but this solution works. If you want the legend to look right, you'll want to merge the input data and fitted values into a single data.frame.
Related
My apologize for my bad english i'm a student from france.
I have a little problem with a function in R, indeed i have a dataframe like that :
https://imgur.com/G5ToQrL
With this code :
testtransect2$TOTAL<-testtransect2$TOTAL*-1
plot(testtransect2$DECA,testtransect2$TOTAL,asp = 1)
xl <- seq(min(testtransect2$DECA),max(testtransect2$DECA), (max(testtransect2$DECA)-min(testtransect2$DECA))/1000)
lines(xl, predict(loess(testtransect2$TOTAL~testtransect2$DECA,span = 0.25), newdata=xl))
I want to create a plot with a smooth line which pass through all the point in the order of the dataframe but when i want put my line with my value xl and predict my plot is not like i want :
https://imgur.com/cSlhNtV
I link you a plot where you can see what i want :
https://imgur.com/mnVgvQ7
i think it's a problem of order in my xl value but i can't do it, if you have any solution
Thanks for give it to me
You can use ggplot
Storing your dataframe in df
df <- data.frame(DECA=c(0,10,15,-23,15,40,90,140,190,250,310,370,420),
TOTAL=c(0,-9,-15,-31.5,-48,-50,-44,-24,-17,-10,-6,-5,0))
You are interested in geom_point and geom_line. You can specify df$DECA and df$TOTAL in aes like this:
library(ggplot)
ggplot(df, aes(x=DECA, y=TOTAL)) +
geom_line() + geom_point()
Yielding
The "but when i want put my line with my value xl and predict my plot is not like i want" part is unfortunately unclear to me, please rephrase if this solution does not work for you.
Updated
There are other smooth_lines that may be added, eg. geom_smooth. Is this what you request?
ggplot(df, aes(x=DECA, y=TOTAL)) +
geom_line() + geom_point() +
geom_smooth(se=F, method = lm, col="red") + #linear method
geom_smooth(se=F, col="green") # loess method
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))
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))
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.
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")
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
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
The follwing command:
ggplot(s, aes(x = I5, y = Success))+geom_point(size=3, alpha=0.4)+
stat_smooth(method="loess", colour="blue", size=1.5)+
xlab("I5")+
ylab("Probability of Success")+
theme_bw()
gives me the following plot:
I would like to get what corresponds to the blue line as a function so that I can apply it to any value.
Is there a way to do that?
If you need the actual loess fit, it's probably better to run it yourself. Let's create some sample data (it would have been nice if you had include some in your original question)
dd <- data.frame(
x=1:50,
y = cumsum(rnorm(50))
)
And now we can run the loess function ourself
sm <- loess(y~x, dd)
Now we can compare the line that ggplot draws to our loess curve
ggplot(dd, aes(x,y)) +
stat_smooth(method="loess") +
geom_point(data=data.frame(x=sm$x, y=predict(sm)), col="red")
We can see these line up perfectly. This we can just use the predict() function with our loess object to get a value for any point. For example
predict(sm, 5)
# [1] -2.922876
I'm trying to plot a scatter-plot with two layers. The reason is I want to represent the size of the points by its number of answers. Then I need to have a smooth-curve layed over it. So I use two datasets to achieve this.
The problem is, when I lay the second layer with the smoother using the original dataset, then the smoother is shifted by one point on the x-scale to the left.
Does anyone know, how to correct this in the R code? Is there maybe something wrong in it?
I thought about to add 1 to the x variable, but I don't want to have to go this far.
library(ggplot2)
q.tab <- xtabs(~x + y, mydata)
q.df <- as.data.frame(q.tab)
pointsize <- q.df$Freq
qplot(x, y, data=q.df) + geom_point(aes(size=as.factor(pointsize)))
+ geom_smooth(data=mydata, method="loess", span=1))
With ggplot2 , when you think in terms of layer it is better to use ggplot function and not qplot.
I generate your data (sample function is very convenient to generate data)
mydata$x <- sample(1:10,100,replace=TRUE)
mydata$y <- sample(1:10,100,replace=TRUE)
q.tab <- xtabs(~x + y, mydata)
q.df <- as.data.frame(q.tab)
ggplot version:
library(ggplot2)
ggplot(data=mydata,aes(x,y,size=Freq)) +
geom_point() +
geom_smooth( method="loess", span=1)
qplot version:
qplot(data=mydata,x=x,y=y,size=Freq,geom='point')+
geom_smooth( method="loess", span=1)
I am trying to produce something similar to densityplot() from the lattice package, using ggplot2 after using multiple imputation with the mice package. Here is a reproducible example:
require(mice)
dt <- nhanes
impute <- mice(dt, seed = 23109)
x11()
densityplot(impute)
Which produces:
I would like to have some more control over the output (and I am also using this as a learning exercise for ggplot). So, for the bmi variable, I tried this:
bar <- NULL
for (i in 1:impute$m) {
foo <- complete(impute,i)
foo$imp <- rep(i,nrow(foo))
foo$col <- rep("#000000",nrow(foo))
bar <- rbind(bar,foo)
}
imp <-rep(0,nrow(impute$data))
col <- rep("#D55E00", nrow(impute$data))
bar <- rbind(bar,cbind(impute$data,imp,col))
bar$imp <- as.factor(bar$imp)
x11()
ggplot(bar, aes(x=bmi, group=imp, colour=col)) + geom_density()
+ scale_fill_manual(labels=c("Observed", "Imputed"))
which produces this:
So there are several problems with it:
The colours are wrong. It seems my attempt to control the colours is completely wrong/ignored
There are unwanted horizontal and vertical lines
I would like the legend to show Imputed and Observed but my code gives the error invalid argument to unary operator
Moreover, it seems like quite a lot of work to do what is accomplished in one line with densityplot(impute) - so I wondered if I might be going about this in the wrong way entirely ?
Edit: I should add the fourth problem, as noted by #ROLO:
.4. The range of the plots seems to be incorrect.
The reason it is more complicated using ggplot2 is that you are using densityplot from the mice package (mice::densityplot.mids to be precise - check out its code), not from lattice itself. This function has all the functionality for plotting mids result classes from mice built in. If you would try the same using lattice::densityplot, you would find it to be at least as much work as using ggplot2.
But without further ado, here is how to do it with ggplot2:
require(reshape2)
# Obtain the imputed data, together with the original data
imp <- complete(impute,"long", include=TRUE)
# Melt into long format
imp <- melt(imp, c(".imp",".id","age"))
# Add a variable for the plot legend
imp$Imputed<-ifelse(imp$".imp"==0,"Observed","Imputed")
# Plot. Be sure to use stat_density instead of geom_density in order
# to prevent what you call "unwanted horizontal and vertical lines"
ggplot(imp, aes(x=value, group=.imp, colour=Imputed)) +
stat_density(geom = "path",position = "identity") +
facet_wrap(~variable, ncol=2, scales="free")
But as you can see the ranges of these plots are smaller than those from densityplot. This behaviour should be controlled by parameter trim of stat_density, but this seems not to work. After fixing the code of stat_density I got the following plot:
Still not exactly the same as the densityplot original, but much closer.
Edit: for a true fix we'll need to wait for the next major version of ggplot2, see github.
You can ask Hadley to add a fortify method for this mids class. E.g.
fortify.mids <- function(x){
imps <- do.call(rbind, lapply(seq_len(x$m), function(i){
data.frame(complete(x, i), Imputation = i, Imputed = "Imputed")
}))
orig <- cbind(x$data, Imputation = NA, Imputed = "Observed")
rbind(imps, orig)
}
ggplot 'fortifies' non-data.frame objects prior to plotting
ggplot(fortify.mids(impute), aes(x = bmi, colour = Imputed,
group = Imputation)) +
geom_density() +
scale_colour_manual(values = c(Imputed = "#000000", Observed = "#D55E00"))
note that each ends with a '+'. Otherwise the command is expected to be complete. This is why the legend did not change. And the line starting with a '+' resulted in the error.
You can melt the result of fortify.mids to plot all variables in one graph
library(reshape)
Molten <- melt(fortify.mids(impute), id.vars = c("Imputation", "Imputed"))
ggplot(Molten, aes(x = value, colour = Imputed, group = Imputation)) +
geom_density() +
scale_colour_manual(values = c(Imputed = "#000000", Observed = "#D55E00")) +
facet_wrap(~variable, scales = "free")