我可以将 direct.label() 与 ggplot 的 scale_colour_manual() 一起使用吗?

发布于 2024-09-11 10:56:55 字数 517 浏览 4 评论 0原文

以下代码将红色和黑色的手动色标分配给我的点:

require(ggplot2)
require(directlabels)
dtest <- data.frame(x=1:20,
                  y=rnorm(20,0,5),
                  v=seq(1,2))
p <- ggplot(dtest, aes(x=x,y=y,color=as.factor(v))) + geom_point() + scale_colour_manual(values=c("red","black"))
p #this looks good; red and black as intended

direct.label(p) #this falls back on the default colors

但是当我将 direct.label() 应用于同一图时,它会覆盖色标以支持 ggplot 默认。有办法防止这种情况吗?如果没有,将新颜色分配给默认 ggplot 比例的最佳方法是什么? 谢谢, 马特

The following code assigns a manual color scale of red and black to my points:

require(ggplot2)
require(directlabels)
dtest <- data.frame(x=1:20,
                  y=rnorm(20,0,5),
                  v=seq(1,2))
p <- ggplot(dtest, aes(x=x,y=y,color=as.factor(v))) + geom_point() + scale_colour_manual(values=c("red","black"))
p #this looks good; red and black as intended

direct.label(p) #this falls back on the default colors

But when I apply direct.label() to the same plot, it overrides the color scale in favor of the ggplot default. Is there a way to prevent this? If not, what's the best way to assign new colors to the default ggplot scale?
Thanks,
Matt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

农村范ル 2024-09-18 10:56:55

发生这种情况是因为 direct.label(p) 通过将标签 geom 添加到 p 进行操作,然后隐藏颜色图例,因为两次标记颜色是多余的。隐藏颜色图例的一种方法是添加scale_colour_discrete(legend=FALSE),这就是我在 direct.label 内部所做的。因此,当 directlabels 应用scale_colour_discrete时,您的scale_colour_manual将会丢失。解决方法是使用以下习惯用法:

p <- ggplot(...)
direct.label(p)+
  scale_colour_manual(...)

This happens because direct.label(p) operates by adding the label geom to p, then by hiding the color legend, since labeling the colors twice would be redundant. One way to hide the color legend is by adding scale_colour_discrete(legend=FALSE), and this is what I do inside of direct.label. So when directlabels applies scale_colour_discrete, your scale_colour_manual will be lost. The workaround is to use the following idiom:

p <- ggplot(...)
direct.label(p)+
  scale_colour_manual(...)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文