我可以将 direct.label() 与 ggplot 的 scale_colour_manual() 一起使用吗?
以下代码将红色和黑色的手动色标分配给我的点:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为 direct.label(p) 通过将标签 geom 添加到 p 进行操作,然后隐藏颜色图例,因为两次标记颜色是多余的。隐藏颜色图例的一种方法是添加scale_colour_discrete(legend=FALSE),这就是我在 direct.label 内部所做的。因此,当 directlabels 应用scale_colour_discrete时,您的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: