I would like to plot each column of a dataframe to a separate layer in ggplot2.
Building the plot layer by layer works well:
df<-data.frame(x1=c(1:5),y1=c(2.0,5.4,7.1,4.6,5.0),y2=c(0.4,9.4,2.9,5.4,1.1),y3=c(2.4,6.6,8.1,5.6,6.3))
ggplot(data=df,aes(df[,1]))+geom_line(aes(y=df[,2]))+geom_line(aes(y=df[,3]))
Is there a way to plot all available columns at ones by using a single function?
I tried to do it this way but it does not work:
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in seq(2:ncol(df))){
p<-p+geom_line(aes(y=df[,i]))
}
return(p)
}
plotAllLayers(df)
One approach would be to reshape your data frame from wide format to long format using function melt() from library reshape2. In new data frame you will have x1 values, variable that determine from which column data came, and value that contains all original y values.
Now you can plot all data with one ggplot() and geom_line() call and use variable to have for example separate color for each line.
library(reshape2)
df.long<-melt(df,id.vars="x1")
head(df.long)
x1 variable value
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color=variable))+geom_line()
If you really want to use for() loop (not the best way) then you should use names(df)[-1] instead of seq(). This will make vector of column names (except first column). Then inside geom_line() use aes_string(y=i) to select column by their name.
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in names(df)[-1]){
p<-p+geom_line(aes_string(y=i))
}
return(p)
}
plotAllLayers(df)
I tried the melt method on a large messy dataset and wished for a faster, cleaner method. This for loop uses eval() to build the desired plot.
fields <- names(df_normal) # index, var1, var2, var3, ...
p <- ggplot( aes(x=index), data = df_normal)
for (i in 2:length(fields)) {
loop_input = paste("geom_smooth(aes(y=",fields[i],",color='",fields[i],"'))", sep="")
p <- p + eval(parse(text=loop_input))
}
p <- p + guides( color = guide_legend(title = "",) )
p
This ran a lot faster then a large melted dataset when I tested.
I also tried the for loop with aes_string(y=fields[i], color=fields[i]) method, but couldn't get the colors to be differentiated.
For the OP's situation, I think pivot_longer is best. But today I had a situation that did not seem amenable to pivoting, so I used the following code to create layers programmatically. I did not need to use eval().
data_tibble <- tibble(my_var = c(650, 1040, 1060, 1150, 1180, 1220, 1280, 1430, 1440, 1440, 1470, 1470, 1480, 1490, 1520, 1550, 1560, 1560, 1600, 1600, 1610, 1630, 1660, 1740, 1780, 1800, 1810, 1820, 1830, 1870, 1910, 1910, 1930, 1940, 1940, 1940, 1980, 1990, 2000, 2060, 2080, 2080, 2090, 2100, 2120, 2140, 2160, 2240, 2260, 2320, 2430, 2440, 2540, 2550, 2560, 2570, 2610, 2660, 2680, 2700, 2700, 2720, 2730, 2790, 2820, 2880, 2910, 2970, 2970, 3030, 3050, 3060, 3080, 3120, 3160, 3200, 3280, 3290, 3310, 3320, 3340, 3350, 3400, 3430, 3540, 3550, 3580, 3580, 3620, 3640, 3650, 3710, 3820, 3820, 3870, 3980, 4060, 4070, 4160, 4170, 4170, 4220, 4300, 4320, 4350, 4390, 4430, 4450, 4500, 4650, 4650, 5080, 5160, 5160, 5460, 5490, 5670, 5680, 5760, 5960, 5980, 6060, 6120, 6190, 6480, 6760, 7750, 8390, 9560))
# This is a normal histogram
plot <- data_tibble %>%
ggplot() +
geom_histogram(aes(x=my_var, y = ..density..))
# We prepare layers to add
stat_layers <- tibble(distribution = c("lognormal", "gamma", "normal"),
fun = c(dlnorm, dgamma, dnorm),
colour = c("red", "green", "yellow")) %>%
mutate(args = map(distribution, MASS::fitdistr, x=data_tibble$my_var)) %>%
mutate(args = map(args, ~as.list(.$estimate))) %>%
select(-distribution) %>%
pmap(stat_function)
# Final Plot
plot + stat_layers
The idea is that you organize a tibble with the arguments that you want to plug into a geom/stat function. Each row should correspond to a + layer that you want to add to the ggplot. Then use pmap. This creates a list of layers that you can simply add to your plot.
Reshaping your data so you don't need the loop is the best option. Otherwise with newer versions of ggplot, you can use the .data pronoun inside the aes(). You can do
plotAllLayers<-function(df){
p <- ggplot(data=df, aes(df[,1]))
for(i in names(df)[2:ncol(df)]){
p <- p + geom_line(aes(y=.data[[i]]))
}
return(p)
}
plotAllLayers(df)
We use the .data pronoun to get at the data passed to the ggplot object, and we iterate over the column names because .data doesn't like indexes for some reason.
Related
I would like to plot each column of a dataframe to a separate layer in ggplot2.
Building the plot layer by layer works well:
df<-data.frame(x1=c(1:5),y1=c(2.0,5.4,7.1,4.6,5.0),y2=c(0.4,9.4,2.9,5.4,1.1),y3=c(2.4,6.6,8.1,5.6,6.3))
ggplot(data=df,aes(df[,1]))+geom_line(aes(y=df[,2]))+geom_line(aes(y=df[,3]))
Is there a way to plot all available columns at ones by using a single function?
I tried to do it this way but it does not work:
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in seq(2:ncol(df))){
p<-p+geom_line(aes(y=df[,i]))
}
return(p)
}
plotAllLayers(df)
One approach would be to reshape your data frame from wide format to long format using function melt() from library reshape2. In new data frame you will have x1 values, variable that determine from which column data came, and value that contains all original y values.
Now you can plot all data with one ggplot() and geom_line() call and use variable to have for example separate color for each line.
library(reshape2)
df.long<-melt(df,id.vars="x1")
head(df.long)
x1 variable value
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color=variable))+geom_line()
If you really want to use for() loop (not the best way) then you should use names(df)[-1] instead of seq(). This will make vector of column names (except first column). Then inside geom_line() use aes_string(y=i) to select column by their name.
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in names(df)[-1]){
p<-p+geom_line(aes_string(y=i))
}
return(p)
}
plotAllLayers(df)
I tried the melt method on a large messy dataset and wished for a faster, cleaner method. This for loop uses eval() to build the desired plot.
fields <- names(df_normal) # index, var1, var2, var3, ...
p <- ggplot( aes(x=index), data = df_normal)
for (i in 2:length(fields)) {
loop_input = paste("geom_smooth(aes(y=",fields[i],",color='",fields[i],"'))", sep="")
p <- p + eval(parse(text=loop_input))
}
p <- p + guides( color = guide_legend(title = "",) )
p
This ran a lot faster then a large melted dataset when I tested.
I also tried the for loop with aes_string(y=fields[i], color=fields[i]) method, but couldn't get the colors to be differentiated.
For the OP's situation, I think pivot_longer is best. But today I had a situation that did not seem amenable to pivoting, so I used the following code to create layers programmatically. I did not need to use eval().
data_tibble <- tibble(my_var = c(650, 1040, 1060, 1150, 1180, 1220, 1280, 1430, 1440, 1440, 1470, 1470, 1480, 1490, 1520, 1550, 1560, 1560, 1600, 1600, 1610, 1630, 1660, 1740, 1780, 1800, 1810, 1820, 1830, 1870, 1910, 1910, 1930, 1940, 1940, 1940, 1980, 1990, 2000, 2060, 2080, 2080, 2090, 2100, 2120, 2140, 2160, 2240, 2260, 2320, 2430, 2440, 2540, 2550, 2560, 2570, 2610, 2660, 2680, 2700, 2700, 2720, 2730, 2790, 2820, 2880, 2910, 2970, 2970, 3030, 3050, 3060, 3080, 3120, 3160, 3200, 3280, 3290, 3310, 3320, 3340, 3350, 3400, 3430, 3540, 3550, 3580, 3580, 3620, 3640, 3650, 3710, 3820, 3820, 3870, 3980, 4060, 4070, 4160, 4170, 4170, 4220, 4300, 4320, 4350, 4390, 4430, 4450, 4500, 4650, 4650, 5080, 5160, 5160, 5460, 5490, 5670, 5680, 5760, 5960, 5980, 6060, 6120, 6190, 6480, 6760, 7750, 8390, 9560))
# This is a normal histogram
plot <- data_tibble %>%
ggplot() +
geom_histogram(aes(x=my_var, y = ..density..))
# We prepare layers to add
stat_layers <- tibble(distribution = c("lognormal", "gamma", "normal"),
fun = c(dlnorm, dgamma, dnorm),
colour = c("red", "green", "yellow")) %>%
mutate(args = map(distribution, MASS::fitdistr, x=data_tibble$my_var)) %>%
mutate(args = map(args, ~as.list(.$estimate))) %>%
select(-distribution) %>%
pmap(stat_function)
# Final Plot
plot + stat_layers
The idea is that you organize a tibble with the arguments that you want to plug into a geom/stat function. Each row should correspond to a + layer that you want to add to the ggplot. Then use pmap. This creates a list of layers that you can simply add to your plot.
Reshaping your data so you don't need the loop is the best option. Otherwise with newer versions of ggplot, you can use the .data pronoun inside the aes(). You can do
plotAllLayers<-function(df){
p <- ggplot(data=df, aes(df[,1]))
for(i in names(df)[2:ncol(df)]){
p <- p + geom_line(aes(y=.data[[i]]))
}
return(p)
}
plotAllLayers(df)
We use the .data pronoun to get at the data passed to the ggplot object, and we iterate over the column names because .data doesn't like indexes for some reason.
I am trying to use the R merge function to combine two data.frames, but keep getting the following error:
Error in fix.by(by.y, y) : 'by' must specify a uniquely valid column
I am not sure what this error means or how to resolve it.
My code thus far is the following:
movies <- read_csv("movies.csv")
firsts = vector(length = nrow(movies))
for (i in 1:nrow(movies)) {
firsts[i] = movies$director[i] %>% str_split(" ", n = 2) %>% unlist %>% .[1]
}
movies$firsts = firsts
movies <- movies[-c(137, 147, 211, 312, 428, 439, 481, 555, 602, 830, 850, 1045, 1080, 1082, 1085, 1096, 1255, 1258, 1286, 1293, 1318, 1382, 1441, 1456, 1494, 1509, 1703, 1719, 1735, 1944, 1968, 1974, 1977, 2098, 2197, 2409, 2516, 2546, 2722, 2751, 2988, 3191,
3227, 3270, 3283, 3285, 3286, 3292, 3413, 3423, 3470, 3480, 3511, 3676, 3698, 3826, 3915, 3923, 3954, 4165, 4381, 4385, 4390, 4397, 4573, 4711, 4729, 4774, 4813, 4967, 4974, 5018, 5056, 5258, 5331, 5405, 5450, 5469, 5481, 4573, 5708, 5715, 5786, 5886, 5888, 5933, 5934, 6052, 6091, 6201, 6234, 6236, 6511, 6544, 6551, 6562, 6803, 4052, 4121, 4326),]
movies <- movies[-c(4521,5846),]
g <- gender_df(movies, name_col = "firsts", year_col = "year", method = c("ssa"))
merge(movies, g, by = c("firsts", "name"), all = FALSE)
I thinks you are trying to give the by argument a non-valid value. Indeed, the documentation tells:
By default the data frames are merged on the columns with names they
both have, but separate specifications of the columns can be given by
by.x and by.y. The rows in the two data frames that match on the
specified columns are extracted, and joined together. If there is more
than one match, all possible matches contribute one row each. For the
precise meaning of ‘match’, see match.
In your case, you shall try the following:
merge(x = movies,y = g, by.x = "firsts", by.y = "name", all = FALSE)
Chemist here (so not very good with statistical analysis) and novice in R:
I have various sets of data where the yield of a reaction is monitored with time such as:
The data:
df <- structure(list(time = c(15, 30, 45, 60, 75, 90, 105, 120, 135,
150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330,
345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 495, 510, 525,
540, 555, 570, 585, 600, 615, 630, 645, 660, 675, 690, 705, 720,
735, 750, 765, 780, 795, 810, 825, 840, 855, 870, 885, 900, 915,
930, 945, 960, 975, 990, 1005, 1020, 1035, 1050, 1065, 1080,
1095, 1110, 1125, 1140, 1155, 1170, 1185, 1200, 1215, 1230, 1245,
1260, 1275, 1290, 1305, 1320, 1335, 1350, 1365, 1380, 1395, 1410,
1425, 1440, 1455, 1470, 1485, 1500, 1515, 1530, 1545, 1560, 1575,
1590, 1605, 1620, 1635, 1650, 1665, 1680, 1695, 1710, 1725, 1740,
1755, 1770, 1785, 1800, 1815, 1830, 1845, 1860, 1875, 1890, 1905,
1920, 1935, 1950, 1965, 1980, 1995, 2010, 2025, 2040, 2055, 2070,
2085, 2100, 2115, 2130), yield = c(9.3411, 9.32582, 10.5475,
13.5358, 17.3376, 16.7444, 20.7234, 19.8374, 24.327, 27.4162,
27.38, 31.3926, 29.3289, 32.2556, 33.0025, 35.3358, 35.8986,
40.1859, 40.3886, 42.2828, 41.23, 43.8108, 43.9391, 43.9543,
48.0524, 47.8295, 48.674, 48.2456, 50.2641, 50.7147, 49.6828,
52.8877, 51.7906, 57.2553, 53.6175, 57.0186, 57.6598, 56.4049,
57.1446, 58.5464, 60.7213, 61.0584, 57.7481, 59.9151, 64.475,
61.2322, 63.5167, 64.6289, 64.4245, 62.0048, 65.5821, 65.8275,
65.7584, 68.0523, 65.4874, 68.401, 68.1503, 67.8713, 69.5478,
69.9774, 73.4199, 66.7266, 70.4732, 67.5119, 69.6107, 70.4911,
72.7592, 69.3821, 72.049, 70.2548, 71.6336, 70.6215, 70.8611,
72.0337, 72.2842, 76.0792, 75.2526, 72.7016, 73.6547, 75.6202,
76.5013, 74.2459, 76.033, 78.4803, 76.3058, 73.837, 74.795, 76.2126,
75.1816, 75.3594, 79.9158, 77.8157, 77.8152, 75.3712, 78.3249,
79.1198, 77.6184, 78.1244, 78.1741, 77.9305, 79.7576, 78.0261,
79.8136, 75.5314, 80.2177, 79.786, 81.078, 78.4183, 80.8013,
79.3855, 81.5268, 78.416, 78.9021, 79.9394, 80.8221, 81.241,
80.6111, 79.7504, 81.6001, 80.7021, 81.1008, 82.843, 82.2716,
83.024, 81.0381, 80.0248, 85.1418, 83.1229, 83.3334, 83.2149,
84.836, 79.5156, 81.909, 81.1477, 85.1715, 83.7502, 83.8336,
83.7595, 86.0062, 84.9572, 86.6709, 84.4124)), .Names = c("time",
"yield"), row.names = c(NA, -142L), class = "data.frame")
What i want to do to the data:
I need to smooth the data in order to plot the 1st derivative. In the paper the author mentioned that one can fit a high order polynomial and use that to do the processing which i think is wrong since we dont really know the true relationship between time and yield for the data and is definitely not polyonymic. I tried regardless and the plot of the derivative did not make any chemical sense as expected. Next i looked into loess using: loes<-loess(Yield~Time,data=df,span=0.9) which gave a much better fit. However, the best results so far was using :
spl <- smooth.spline(df$Time, y=df$Yield,cv=TRUE)
colnames(predspl)<-c('Time','Yield')
pred.der<-as.data.frame(predict(spl, deriv=1))
colnames(pred.der)<-c('Time', 'Yield')
which gave the best fit especially in the initial data points (by visual inspection).
The problem i have:
The issue however is that the derivative looks really good only up to t=500s and then it starts wiggling more and more towards the end. This shouldnt happen from a chemistry point of view and it is just a result of overfitting towards the end of the data due to the increase of the noise. I know this since for some experiments that i have performed 3 times and averaged the data (so the noise decreased) the wiggling is much smaller in the plot of the derivative.
What i have tried so far:
I tried different values of spar which although it smoothens correctly the later data it causes a poor fit in the initial data (which are the most important). I also tried to reduce the number of knots but i got a similar result with the one from changing the spar value. What i think i need is to have a larger amount of knots in the begining which will smoothly decrease to a small number of knots towards the end to avoid that overfitting.
The question:
Is my reasoning correct here? Does anyone know how can i have the above effect in order to get a smooth derivative without any wiggling? Do i need to try a different fit other than the spline maybe? I have attached a pic in the end where you can see the derivative from the smooth.spline vs time and a black line (drawn by hand) of what it should look like. Thank you for your help in advance.
I think you're on the right track on having more closely spaced knots for the spline at the start of the curve. You can specify knot locations for smooth.spline using all.knots (at least on R >= 3.4.3; I skimmed the release notes for R, but couldn't pinpoint the version where this became available).
Below is an example, and the resulting, smoother fit for the derivative after some manual work of trying out different knot positions:
with(df, {
kn <- c(0, c(50, 100, 200, 350, 500, 1500) / max(time), 1)
s <- smooth.spline(time, yield, cv = T)
s2 <- smooth.spline(time, yield, all.knots = kn)
ds <- predict(s, d = 1)
ds2 <- predict(s2, d = 1)
np <- list(mfrow = c(2, 1), mar = c(4, 4, 1, 2))
withr::with_par(np, {
plot(time, yield)
lines(s)
lines(s2, lty = 2, col = 'red')
plot(ds, type = 'l', ylim = c(0, 0.15))
lines(ds2, lty = 2, col = 'red')
})
})
You can probably fine tune the locations further, but I wouldn't be too concerned about it. The primary fits are already near enough indistinguishable, and I'd say you're asking quite a lot from these data in terms of identifying details about the derivative (this should be evident if you plot(time[-1], diff(yield) / diff(time)) which gives you an impression about the level of information your data carry about the derivative).
Created on 2018-02-15 by the reprex package (v0.2.0).
I am trying to fit curves to the following scatter plot with ggplot2.
I found the geom_smooth function, but trying different methods and spans, I never seem to get the curves right...
This is my scatter plot:
And this is my best attempt:
Can anyone get better curves that fit correctly and don't look so wiggly? Thanks!
Find a MWE below:
my.df <- data.frame(sample=paste("samp",1:60,sep=""),
reads=c(523, 536, 1046, 1071, 2092, 2142, 4184, 4283, 8367, 8566, 16734, 17132, 33467, 34264, 66934, 68528, 133867, 137056, 267733, 274112, 409, 439, 818, 877, 1635, 1754, 3269, 3508, 6538, 7015, 13075, 14030, 26149, 28060, 52297, 56120, 104594, 112240, 209188, 224479, 374, 463, 748, 925, 1496, 1850, 2991, 3699, 5982, 7397, 11963, 14794, 23925, 29587, 47850, 59174, 95699, 118347, 191397, 236694),
number=c(17, 14, 51, 45, 136, 130, 326, 333, 742, 738, 1637, 1654, 3472, 3619, 7035, 7444, 13133, 13713, 21167, 21535, 11, 22, 30, 44, 108, 137, 292, 349, 739, 853, 1605, 1832, 3099, 3565, 5287, 5910, 7832, 8583, 10429, 11240, 21, 43, 82, 124, 208, 296, 421, 568, 753, 908, 1127, 1281, 1448, 1608, 1723, 1854, 1964, 2064, 2156, 2259),
condition=rep(paste("cond",1:3,sep=""), each=20))
png(filename="TEST1.png", height=800, width=1000)
print(#or ggsave()
ggplot(data=my.df, aes(x=reads, y=log2(number+1), group=condition, color=condition)) +
geom_point()
)
dev.off()
png(filename="TEST2.png", height=800, width=1000)
print(#or ggsave()
ggplot(data=my.df, aes(x=reads, y=log2(number+1), group=condition, color=condition)) +
geom_point() +
geom_smooth(se=FALSE, method="loess", span=0.5)
)
dev.off()
This is a very broad question, as you're effectively looking for a model with less variance (more bias), of which there are many. Here's one:
ggplot(data = my.df,
aes(x = reads, y = log2(number + 1), color = condition)) +
geom_point() +
geom_smooth(se = FALSE, method = "gam", formula = y ~ s(log(x)))
For documentation, see ?mgcv::gam or a suitable text on modeling. Depending on your use case, it may make more sense to make your model outside of ggplot.
I would like to plot each column of a dataframe to a separate layer in ggplot2.
Building the plot layer by layer works well:
df<-data.frame(x1=c(1:5),y1=c(2.0,5.4,7.1,4.6,5.0),y2=c(0.4,9.4,2.9,5.4,1.1),y3=c(2.4,6.6,8.1,5.6,6.3))
ggplot(data=df,aes(df[,1]))+geom_line(aes(y=df[,2]))+geom_line(aes(y=df[,3]))
Is there a way to plot all available columns at ones by using a single function?
I tried to do it this way but it does not work:
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in seq(2:ncol(df))){
p<-p+geom_line(aes(y=df[,i]))
}
return(p)
}
plotAllLayers(df)
One approach would be to reshape your data frame from wide format to long format using function melt() from library reshape2. In new data frame you will have x1 values, variable that determine from which column data came, and value that contains all original y values.
Now you can plot all data with one ggplot() and geom_line() call and use variable to have for example separate color for each line.
library(reshape2)
df.long<-melt(df,id.vars="x1")
head(df.long)
x1 variable value
1 1 y1 2.0
2 2 y1 5.4
3 3 y1 7.1
4 4 y1 4.6
5 5 y1 5.0
6 1 y2 0.4
ggplot(df.long,aes(x1,value,color=variable))+geom_line()
If you really want to use for() loop (not the best way) then you should use names(df)[-1] instead of seq(). This will make vector of column names (except first column). Then inside geom_line() use aes_string(y=i) to select column by their name.
plotAllLayers<-function(df){
p<-ggplot(data=df,aes(df[,1]))
for(i in names(df)[-1]){
p<-p+geom_line(aes_string(y=i))
}
return(p)
}
plotAllLayers(df)
I tried the melt method on a large messy dataset and wished for a faster, cleaner method. This for loop uses eval() to build the desired plot.
fields <- names(df_normal) # index, var1, var2, var3, ...
p <- ggplot( aes(x=index), data = df_normal)
for (i in 2:length(fields)) {
loop_input = paste("geom_smooth(aes(y=",fields[i],",color='",fields[i],"'))", sep="")
p <- p + eval(parse(text=loop_input))
}
p <- p + guides( color = guide_legend(title = "",) )
p
This ran a lot faster then a large melted dataset when I tested.
I also tried the for loop with aes_string(y=fields[i], color=fields[i]) method, but couldn't get the colors to be differentiated.
For the OP's situation, I think pivot_longer is best. But today I had a situation that did not seem amenable to pivoting, so I used the following code to create layers programmatically. I did not need to use eval().
data_tibble <- tibble(my_var = c(650, 1040, 1060, 1150, 1180, 1220, 1280, 1430, 1440, 1440, 1470, 1470, 1480, 1490, 1520, 1550, 1560, 1560, 1600, 1600, 1610, 1630, 1660, 1740, 1780, 1800, 1810, 1820, 1830, 1870, 1910, 1910, 1930, 1940, 1940, 1940, 1980, 1990, 2000, 2060, 2080, 2080, 2090, 2100, 2120, 2140, 2160, 2240, 2260, 2320, 2430, 2440, 2540, 2550, 2560, 2570, 2610, 2660, 2680, 2700, 2700, 2720, 2730, 2790, 2820, 2880, 2910, 2970, 2970, 3030, 3050, 3060, 3080, 3120, 3160, 3200, 3280, 3290, 3310, 3320, 3340, 3350, 3400, 3430, 3540, 3550, 3580, 3580, 3620, 3640, 3650, 3710, 3820, 3820, 3870, 3980, 4060, 4070, 4160, 4170, 4170, 4220, 4300, 4320, 4350, 4390, 4430, 4450, 4500, 4650, 4650, 5080, 5160, 5160, 5460, 5490, 5670, 5680, 5760, 5960, 5980, 6060, 6120, 6190, 6480, 6760, 7750, 8390, 9560))
# This is a normal histogram
plot <- data_tibble %>%
ggplot() +
geom_histogram(aes(x=my_var, y = ..density..))
# We prepare layers to add
stat_layers <- tibble(distribution = c("lognormal", "gamma", "normal"),
fun = c(dlnorm, dgamma, dnorm),
colour = c("red", "green", "yellow")) %>%
mutate(args = map(distribution, MASS::fitdistr, x=data_tibble$my_var)) %>%
mutate(args = map(args, ~as.list(.$estimate))) %>%
select(-distribution) %>%
pmap(stat_function)
# Final Plot
plot + stat_layers
The idea is that you organize a tibble with the arguments that you want to plug into a geom/stat function. Each row should correspond to a + layer that you want to add to the ggplot. Then use pmap. This creates a list of layers that you can simply add to your plot.
Reshaping your data so you don't need the loop is the best option. Otherwise with newer versions of ggplot, you can use the .data pronoun inside the aes(). You can do
plotAllLayers<-function(df){
p <- ggplot(data=df, aes(df[,1]))
for(i in names(df)[2:ncol(df)]){
p <- p + geom_line(aes(y=.data[[i]]))
}
return(p)
}
plotAllLayers(df)
We use the .data pronoun to get at the data passed to the ggplot object, and we iterate over the column names because .data doesn't like indexes for some reason.