简体   繁体   中英

R Heatmap using binned columns and rows

I have a very large table (403k rows) which contains some categorical contious performance values (flow, pressure ect.) which I would like to plot against the sold value. I would like to create a heatmap or contour plot from it, using binned values on Q, W, and E, with the heatmap showing the Sales so that I can aggregate the sold values. For the example, lets set the table ( df ) as:

Q<-c(0.5,1,2,3,3.5,4,4,3,3,4,1,2)
W<-c(1,0.5,2,3,3,4,4,2,1,2,2,1)
E<-c(2,2,2,1,1,5,5,2,3,4,4,1)
Sales<-c(5,30,30,5,10,10,5,5,5,12,20,40)
df <- data.frame(Q = Q, W = W, E = E, Sales = Sales)

In my real table, Q is actually value that ranges from 0 to 40, where H ranges from 0 to 20 and P from 20 to 1000. I have tried making a ggplot and scaling the color with ggsci using ggplot(df) + geom_tile(aes(x = Q, y = W, fill = Sales), color = NA) + scale_fill_gsea() however this produces some tiny dots, which are hardly readable (see picture). Hence, I think tile does not bin or aggregate the Q and W values along with Sales(?)

在此处输入图像描述

What I am trying to create is something more like this (ugly) thing which I quickly made in Excel for this example:

在此处输入图像描述

Now I'm no expert at all, so I was hoping that someone out there knows how to plot this in a neat and elegant way, either via a heatmap, or maybe a 2d density plot of some kind?

EDIT : If i use ggplot(df, aes(Q,H)) + geom_hex(color = df$Sales) I get an error, and using just geom_hex() gives me something closer, but the colors does not scale according to the sales amount.

EDIT : Added "half" an answer in the bottom, using geom_bin2d() , which goes along with geom_hex() .

I found a way to accomplish my question (read below). Other suggestions on how to visualize it elegantly are much appreciated!

ggplot(df, aes(x = Q, y = W, z = Sales)) + stat_bin2d(bins = 10) +
  stat_summary_2d(bins = 10, fun = function(x) (x)) +
  stat_summary_2d(bins = 10, aes(label = ..value..), fun = function(x) sum(x), geom="text") +
  scale_fill_gradient(labels = comma, names = "Sales", low = "lightblue", high = "green", trans = "log10") 

在此处输入图像描述

EDIT : Updated my answer. Now the issue is to scale the colour correctly (see image above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM