I have a numeric data frame call A
and a categoriacal one call B
For every two variables (one from B
and one from A
) I want to plot a bar chart.
My try:
y <- unlist(lapply(D, Negate(is.numeric)))
x <- unlist(lapply(D, is.numeric))
A <- D[,x]
B <- D[,y]
A <- as.data.frame(A)
B <- as.data.frame(B)
for(i in (1:ncol(A)))
{
for(j in (1:ncol(B)))
{
ggplot(D, aes(x = A[,i], y = B[,j]))
geom_bar(fill='red')
}
}
But is not plotting anything. I'm not sure if it's necessary to save each plot in a vector and then plot them with another for. Any suggestions would be great!
CodePudding user response:
You will need to wrap the ggplot statement inside the print()
function to generate output while inside a loop:
for(i in (1:ncol(A)))
{
for(j in (1:ncol(B)))
{
g<- ggplot(D, aes(x = A[,i], y = B[,j]))
geom_bar(fill='red')
print(g)
}
}
CodePudding user response:
I think you need to replace geom_bar()
with geom_col()
or to add stat = identity
inside geom_bar()
.
You can also avoid using the for
loop by using pmap
from package purrr
:
df <- expand.grid(
i = 1:ncol(A),
j = 1:ncol(B)
)
purrr::pmap(
list(df$i, df$j),
function(.i, .j){
tmp <-ggplot(D, aes(x = A[,.i], y = B[,.j]))
geom_col(fill='red')
print(tmp)
}
)