Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

r - Continuous color bar with separators instead of ticks

The picture should give a good idea of what I would want to achieve. Ideally, the resulting colour bar would keep a continuous nature, i.e., should be based on a continuous rather than discrete aesthetic, or at least come very close to behave like it.

This also means, not just the simple approach of just bringing the legend keys of a discrete fill close enough together.

Yes, I could create a fake legend, but I'd like a solution that modifies at the legend drawing level.

I would be also very happy with interesting grid hacks!

library(ggplot2)

ggplot(iris, aes(Sepal.Length, y = Sepal.Width, fill = Petal.Length))+
  geom_point(shape = 21) +
  scale_fill_continuous() +
  guides(fill = guide_colorbar(ticks.colour = "black"))

That's photoshopped, apologies!. I don't want to create the arrow, just the continuous scale with separators instead of ticks enter image description here

The ultimate goal is to reproduce a color bar as orignially proposed in this thread enter image description here

However, this is not about creating the discrete gradient bar, this is just about the separators!

The discrete gradient bar is not the problem, there are already solutions out there (e.g., https://stackoverflow.com/a/62544405/7941188, https://stackoverflow.com/a/62556763/7941188, https://stackoverflow.com/a/50540633/7941188)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's certainly a quick grid hack Tjebo, but it probably needs a bit of work to make it robust (indexing by name rather than by number):

library(ggplot2)
library(grid)

p <- ggplot(iris, aes(Sepal.Length, y = Sepal.Width, fill = Petal.Length))+
  geom_point(shape = 21) +
  scale_fill_continuous() +
  guides(fill = guide_colorbar(ticks.colour = "black"))

gt <- ggplot_gtable(ggplot_build(p))

x1 <- gt$grobs[[which(gt$layout$name == "guide-box")]]$grobs[[1]]$grobs[[5]]$x1
x1[1:7] <- x1[8:14]
gt$grobs[[which(gt$layout$name == "guide-box")]]$grobs[[1]]$grobs[[5]]$x1 <- x1
grid.newpage()
grid.draw(gt)

Created on 2020-06-24 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...