Reputation: 7730
I would like to plot simple heatmap using ggplot
library(ggplot2)
my_df <- data.frame(var_1 = sample(c('a','b', 'c'), 1000, replace = TRUE),
var_2 = sample(c('foo', 'bar', 'foo_bar'), 1000, replace = TRUE),
var_3 = sample(c(1,0), 1000, replace = TRUE))
ggplot(data = my_df, aes(x = var_1, y = var_2, fill = var_3)) +
geom_tile()
I cannot understand where there is no color variation. I changed number of rows in sample
function, but always received only two colors in heat map. Any suggestions?
Upvotes: 1
Views: 964
Reputation: 8275
Replace geom_tile
with a layer that computes the statistical transformation you desire:
ggplot(data = my_df, aes(x = var_1, y = var_2)) +
stat_summary_2d(fun = "mean", geom = "tile",
aes(z = var_3, fill = ..value..))
Upvotes: 2
Reputation: 31452
To plot the proportion of 1 and 0 by factor, you will need to calculate the mean of var_3
for each combination of var_1
and var_2
. Here I show how to do that using data.table
, although you could also use dplyr.summarise
or aggregate
from base R.
library(data.table)
setDT(my_df)
ggplot(data = my_df[, var_3 := mean(var_3), by = .(var_1,var_2)],
aes(x = var_1, y = var_2, fill = var_3)) +
geom_tile()
Upvotes: 2
Reputation: 937
that's because the only values you are choosing to input are either 0 or 1 from your vector in your var_3 = sample(c(1,0), 1000, replace = TRUE)
. If instead you want to choose values between 0 and 1, use this code instead:
var_3 = sample(0:10, 1000, replace = TRUE)/10
Upvotes: 3