purrr::map and a problem with setting xlab ylab names

Hello,
I tried to make series of plots from two tibbles (the example is using mtcars only) and I've found that map creates vectors without names. I have no idea how to set xlab and ylab names (based on column names in the tibble) in this case...
Can you help?

a <- function(.x,.y){
  
  o <- ggplot() +
    geom_point(aes(x = .x, y = .y))+
    geom_smooth(aes(x = .x, y = .y), method = lm, se=FALSE)+
    labs(y=names(.y), x=names(.x), title="pozn a obj")
  print(o)
}
for (i in 1:2 ){
  map2(as_tibble(mtcars[,i]), mtcars, a)
}

Hi,

Could you provide a bit more detail on what the output should look like. I can't get that from your code.

Here is something that might help

test = imap(mtcars, function(values, colname){
  ggplot() + geom_point(aes(x = rownames(mtcars), y = values)) +
    labs(x = "Car", y = colname) + theme(axis.text.x = element_text(angle = 90))
})

test[[1]]


test = pmap(list(mtcars, colnames(mtcars), list(rownames(mtcars))), 
            function(values, colname, rownames){
  ggplot() + geom_point(aes(x = rownames, y = values)) +
    labs(x = "Car", y = colname) + theme(axis.text.x = element_text(angle = 90))
})

test[[1]]

Both functions provide the exact same output but the input is a bit different.

imap uses the names and values of a vector you provide it (or in case of a data frame column values and column names). I manually supply the rownames in the function because they are always the same

pmap is like mapply in base R and iterates over every element in a list. If there is only one element, it will repeat it to match the list that is > 1. Here I supplied again the data frame (which it will iterate per column), the column names and a list with all the rownames. It produces the same output.

Hope this helps,
PJ

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Thanks, with your example I managed to get the idea how to use pmap :blush:
The example below does what I need, that is, it takes two different dataframes (here simulated with mtcars, but one without the first and the other without the last column), and plots one column of df1 against one column of df2, applying the proper column names as labels of the y and x axes.

I think imap would not do well here, as I need twice names and values (kinda "imap2" :wink:

test = pmap(list(mtcars[,-11], mtcars[,-1], colnames(mtcars[,-11]), colnames(mtcars[,-1])), 
            function(values1, values2, colname1, colname2){
              ggplot() + geom_point(aes(x = values1, y = values2)) +
                labs(x = colname1, y = colname2)
            })
test[3]

PS Actually, as this might invite other solutions, I used for loop, as I needed to make plots of every df1 column over every df2 column. But the example above can be adapted easily.

1 Like