r - ggplot2: Independent Continuous Fill for Summary Row & Column -
i using strategy plot summary (totals) rows in heatmap using geom_tile
, involves creating rows in data_frame
row , column totals:
library(dplyr) library(ggplot2) entitites = letters[1:10] # create sample data df_foo = bind_cols( data_frame(group1 = rep(c("a", "b"), each = 100)), bind_rows( expand.grid( left = entitites, right = entitites, stringsasfactors = false ), expand.grid( left = entitites, right = entitites, stringsasfactors = false ) ), data_frame(value = rpois(200, 15)) ) # create summary row & column df_foo_aug = bind_rows( df_foo, df_foo %>% group_by(left, group1) %>% summarize( value = sum(value), right = "total" ), df_foo %>% group_by(right, group1) %>% summarize( value = sum(value), left = "total" ) ) # create plot df_foo_aug %>% ggplot(aes(x = right, y = left, fill = value)) + geom_tile() + facet_wrap(~ group1) + theme_bw()
this yields:
obviously, totals row/column need own fill gradient, not clear how (if) can add second continuous/gradient fill.
any other way achieve same intended outcome acceptable solution question well.
the problem here in ggplot
, in principle, aesthetic can have 1 scale. fill
can have 1 scale. however, there ways avoid this, example using color
second scale. alternatively, mess around grobs job done, per shayaa's comment.
here possible examples, using geom_point
display totals:
base_plot <- ggplot(df_foo_aug, aes(x = right, y = left)) + geom_tile(data = filter(df_foo_aug, right != 'total', left != 'total'), aes(fill = value)) + coord_equal() + facet_wrap(~ group1) + scale_y_discrete(limits = rev(sort(unique(df_foo_aug$left)))) + theme_classic() + theme(strip.background = element_blank())
a standard approach:
base_plot + geom_point(data = filter(df_foo_aug, right == 'total' | left == 'total'), aes(col = value), size = 9.2, shape = 15) + scale_color_gradient('total', low = 'black', high = 'red')
using color scales wider perceptual range:
base_plot + geom_point(data = filter(df_foo_aug, right == 'total' | left == 'total'), aes(col = value), size = 9.2, shape = 15) + viridis::scale_fill_viridis(option = 'b') + viridis::scale_color_viridis('total', option = 'd')
also mapping size
total value
:
base_plot + geom_point(data = filter(df_foo_aug, right == 'total' | left == 'total'), aes(col = value, size = value)) + scale_size_area(max_size = 8, guide = 'none') + viridis::scale_fill_viridis(option = 'b') + viridis::scale_color_viridis('total', option = 'd')
personally, quite last one.
one final improvement move y-axis up, recommend cowplot
package.
Comments
Post a Comment