0

I have the following hexbin plot:

enter image description here

I would like the count to start from the lowest possible count, for example 10, and show that with different colour. Note that the lowest count differs with different datasets. Therefore, it is difficult to set it to a specific number. The script that I have written to generate the plot is:

d <- ggplot(selectedDF, aes(BEC_Agg, AC)) + geom_hex(bins = 30) + theme_bw() +
    theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n")  + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"))

I tried the solution here:

d <- ggplot(selectedDF, aes(BEC_Agg, AC)) + geom_hex(aes(fill=cut(..value..,breaks=pretty(..value..,n=5))),bins = 30) + theme_bw() +
    theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n")  + scale_fill_gradientn(colors = brewer.pal(3,"Dark2"))

But I got the following error:

Error in cut(value, breaks = pretty(value, n = 5)) : 
  object 'value' not found

How can I fix that?

Adam Amin
  • 1,406
  • 2
  • 11
  • 23

2 Answers2

0

You should define the variable value before running ggplot. Since lowest count differs among datasets, you might want to try something like value <- min(count(yourDF)).

Ana
  • 87
  • 9
0

Since your focus is tweaking the legend, here is a method. A sample data is generated as you didn't provide any.

# sample dataframe 
set.seed(77)
x=rnorm(1000, mean = 4, sd = 1)
y=rnorm(1000, mean = 2, sd = 0.5)
df <- data.frame(x,y)
# -------------------------------------------------------------------------
# The following is from your script
base <- ggplot(df, aes(x, y)) + geom_hex(bins = 30) + theme_bw() +
  theme(text = element_text(face = "bold", size = 16)) + xlab("\nNormalized BEC") + ylab("AC\n") 
# -------------------------------------------------------------------------
base_limit_break <- base + scale_fill_continuous(limits = c(1,20), breaks = c(1:20))
# -------------------------------------------------------------------------
# This is the part relevant to your question 
base_limit_break + guides(fill = guide_colorbar(barheight = unit(10, "cm"), reverse = TRUE))

Output

tweak_legend

Community
  • 1
  • 1
deepseefan
  • 3,701
  • 3
  • 18
  • 31