I have this ggplot
ggplot(dt.1, aes(x=pctOAC,y=NoP, fill=Age)) +
geom_bar(stat="identity",position=position_dodge()) +
geom_smooth(aes(x=pctOAC,y=NoP, colour=Age), se=F, method="loess",show_guide = FALSE,lwd=0.7) +
theme(legend.position=c(.2,0.8))
dt1 <- structure(list(Age = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("o80", "u80"), class = "factor"), NoP = c(47L, 5L, 33L, 98L, 287L, 543L, 516L, 222L, 67L, 14L, 13L, 30L, 1L, 6L, 17L, 30L, 116L, 390L, 612L, 451L, 146L, 52L), pctOAC = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)), .Names = c("Age", "NoP", "pctOAC"), row.names = c(NA, -22L), class = "data.frame")
I would like to have the smooth lines constrained to lie above zero, perhaps something similar to a kernel density. In fact if I had the underlying data, I expect a kernel density is exactly what I would want, but I only have the aggregated data. Is there any way to do this ? I tried using different method=
in the geom_smooth
, but the small dataset seems to prevent it. I wondered about using stat_function
but I don't have much clue about how to proceed with finding a suitable function to plot.
The geom smooth function is a function for the ggplot2 visualization package in R. Essentially, geom_smooth() adds a trend line over an existing plot.
In the above example loess() function is used to fit a smooth curve into plot. The lwd parameter is used to specify the line type of the smooth curve. The arguments x and y are used to provide coordination to the plot. The loess function will then set a smooth curve in the plot.
stat_smooth: Add a smoother.Aids the eye in seeing patterns in the presence of overplotting.
A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().
Another possibility is to use method="glm"
with a spline curve and a log link (i.e. also tried method="gam"
, but its automatic complexity adjustment wanted to reduce the wiggliness too much:
library(splines)
ggplot(dt.1, aes(x=pctOAC,y=NoP, fill=Age)) +
geom_bar(stat="identity",position=position_dodge()) +
geom_smooth(aes(colour=Age), se=F,
method="glm",
formula=y~ns(x,8),
family=gaussian(link="log"),
show_guide = FALSE,lwd=0.7) +
theme(legend.position=c(.2,0.8))
How about geom_density()
?
ggplot(dt1, aes(x=pctOAC,y=NoP, colour=Age, fill=Age)) +
geom_bar(stat="identity",position=position_dodge()) +
geom_density(stat="identity", fill=NA) +
theme(legend.position=c(.2,0.8))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With