I am trying to plot some data ranges from 1 to 6 using scale_color_gradientn (ggplot2 package)
based on the following code. By default, guide_color_bar
will put the label as the "center" of the bin in legend (see code block 1). But I would like to set the label to be at the "upper" and "lower" boundary of each bin. I tried to set breaks and labels accordingly, however, the 2,3,4,5 is properly aligned but 1,6 is not showing (see code block2).
Please see code attached.
library(ggplot2)
###provide dataset
dat <- data.frame(list(x = c(0.214137620411313,0.553775825041679,-1.0595195186151,
-1.61004932625145,-0.338151062634607,0.204937753426245,
-0.224345039271189,-0.909609704018834,-0.808109884248038,
0.553083514142192,-0.389177932603183,-0.447245638594407,
-0.0211388451690059,-0.599417455124725,-0.310866189554078,
-0.681632468885545,-0.202055723512808,1.11680032924059,0.82599921267075,1.2509189798129),
y = c(2.60809809498069,-0.051039961195504,2.22719419433773,-0.0138721238155097,-1.54739969676097,
-1.37988910915699,1.47987074083825,-0.254921944338877,-0.326280380145921,-0.726638665692272,
-1.95234864995199,0.422940041768889,1.18168478575317,0.91795937727616,0.0954675468852296,
-1.68443178674375,0.990329350606127,-0.707831781928625,-0.594029169314093,-1.06589703339072)),
z = c(1,3,3,1,2,2,2,4,2,1,1,1,1,5,2,4,3,4,1,4))
###define breaks and colors
my_breaks <- c(0,1,2,3,4,5,6)
colors <- c('#e41a1c','#377eb8','#4daf4a',
'#ff7f00','#ffff33','#a65628')
###the label is in the center.
ggplot(dat, aes(x,y,color=z, label = round(z,2))) + geom_point() +
scale_color_gradientn(
colours = colors,
values = scales::rescale(c(1:6)),
limit = c(1,6),
guide = guide_colourbar(nbin = 6, raster = FALSE, frame.colour = "black", ticks.colour = NA,
direction = "horizontal",
barwidth = 30, barheight = 2, label.hjust = 0)) +
geom_text() +
theme(legend.position = 'bottom')
###the label shows the upper and lower boundary for each bin, but the beginning (1) and ending (6) is not showing.
ggplot(dat, aes(x,y,color=z, label = round(z,2))) + geom_point() +
scale_color_gradientn(
colours = colors,
values = scales::rescale(c(1:6)),
limit = c(1,6),
breaks = c(1:7)-0.5, ###the label should be at 0.5,1.5,2.5,...,6.5
labels = my_breaks,
guide = guide_colourbar(nbin = 6, raster = FALSE, frame.colour = "black", ticks.colour = NA,
direction = "horizontal",
barwidth = 30, barheight = 2, label.hjust = 0)) +
geom_text() +
theme(legend.position = 'bottom')
Any help is appreciated.