tidymodels / corrr

Explore correlations in R
https://corrr.tidymodels.org
Other
588 stars 56 forks source link

New version of / alternative to`rplot` #35

Closed drsimonj closed 5 years ago

drsimonj commented 7 years ago

Below is code for a similar plot to rplot, but making use of geom_tile and geom_text:

library(corrr)

rs <- mtcars %>% correlate() %>% rearrange(absolute = FALSE)

order <- rs %>% 
  select(-rowname) %>% 
  colnames()

rs %>% 
  stretch(na.rm = TRUE) %>%
  mutate_at(c("x", "y"), forcats::fct_relevel, ... = order) %>% 
  ggplot(aes(x, y, fill = r)) +
    geom_tile() +
    geom_text(aes(label = as.character(fashion(r))), color = "white", size = 3) +
    theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
    scale_fill_gradientn(colors = c("darkred", "firebrick2", "goldenrod2", "gray", "springgreen2", "dodgerblue2", "darkblue")) +
    theme_minimal() +
    labs(x = NULL, y = NULL)

new_plot

With some tweaking, it can be applied to cord_df after focus:

rs <- mtcars %>% 
  correlate() %>% 
  focus(mpg:hp)

order <- rs %>% 
  select(-rowname) %>% 
  as.matrix() %>%
  #abs() %>% 
  seriation::seriate()

row_order <- rs$rowname[seriation::get_order(order, dim = 1)]
col_order <- colnames(rs[-1])[seriation::get_order(order, dim = 2)]

rs %>% 
  gather(colname, r, -rowname) %>% 
  mutate(rowname = factor(rowname, levels = row_order),
         colname = factor(colname, levels = col_order)) %>% 
  ggplot(aes(rowname, colname, fill = r)) +
  geom_tile() +
  geom_text(aes(label = as.character(corrr::fashion(r))), color = "white", size = 3) +
  scale_fill_gradientn(colors = c("darkred", "firebrick2", "goldenrod2", "gray", "springgreen2", "dodgerblue2", "darkblue"))

focus_plot

jkaupp commented 7 years ago

I like it. Would suggest using an outline color within geom_tile() with a small width(), either that or people can do things downstream with the plot object. Using the viridis palettes would be another option.

drsimonj commented 7 years ago

Thanks @jkaupp I've been thinking of giving the plots a bit of an overhaul to make it easier for customization like this. Not sure how soon I want to go down that path, but it's in the back of my mind! And viridis is a nice idea, though I'm concerned the colours, particularly yellow, might confuse people. E.g., see another issue about hot v cold. Still, there are some nice options like it :)

drsimonj commented 5 years ago

Closing as issue has been open for over 2 years. Can revisit code if needed.

github-actions[bot] commented 3 years ago

This issue has been automatically locked. If you believe you have found a related problem, please file a new issue (with a reprex: https://reprex.tidyverse.org) and link to this issue.