Ggplot2 correlation grid values

When using facet_grid in ggplot2, I would like to have a correlation value for the subsets of data for each grid cell in the upper right corner of the particular graph.

eg. if it works:

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p + facet_grid(vs ~ am, margins=TRUE) 

I would like to see the correlation value for each of the 9 graphs in the grid somewhere. In this particular case, from the example, I expect each one to be close to -0.9 or so from a visual inspection.

Or maybe an output table to go with a graph that gives correlation values ​​for each of the cells in the table compared to facet_grid ... (this is less desirable, but also an option).

Ideally, I would like to extend this to any other function that I choose so that it can use one or both of the two variables built to calculate statistics.

Is it possible?

Thanks in advance

+6
source share
2 answers

Winston Chang offered an answer to ggplot2 ... that's what he said ... this is not a bad answer ...

You can do something like this:

 p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() # Calculate correlation for each group cors <- ddply(mtcars, c("vs", "am"), summarise, cor = round(cor(mpg, wt), 2)) p + facet_grid(vs ~ am) + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=30, y=4) 

I do not think that this can be done correctly with fields = TRUE. If you need fields, you may need to pre-process your data to add an ALL value for each cut variable.

Winston

+3
source

I would prefer to add (linear) data smoothing. This gives you much more information than correlation.

 ggplot(mtcars, aes(mpg, wt)) + geom_smooth(method = "loess", colour = "red", fill = "red") + geom_smooth(method = "lm", colour = "blue", fill = "blue") + geom_point() + facet_grid(vs ~ am, margins=TRUE) 

enter image description here

 ggplot(mtcars, aes(mpg, wt)) + geom_smooth(method = "lm") + geom_point() + facet_grid(vs ~ am, margins=TRUE) 

enter image description here

+4
source

Source: https://habr.com/ru/post/921165/


All Articles