【问题标题】:ggplot2: cannot override 2nd legend aesthetics when using stat_smoothggplot2:使用 stat_smooth 时无法覆盖第二个图例美学
【发布时间】:2015-08-30 00:45:27
【问题描述】:

南瓜头盔(3.1.2),ggplot2_1.0.0。

library(ggplot2)
some_diamonds <- subset(diamonds, color %in% c('D', 'E', 'F'))
g <- ggplot(some_diamonds, aes(carat, depth, linetype=cut, colour=color)) +
    stat_smooth(se=F) + scale_colour_grey()

所需的颜色美感在 color 的图例中正确显示(并且至关重要的是,在情节本身中),但 cut 的颜色默认为 stat_smooth 的默认颜色(蓝色)。 usual tricks 在这种情况下似乎不起作用,例如:

g <- ggplot(some_diamonds, aes(carat, depth, linetype=cut, colour=color)) + 
   stat_smooth(se=F) 
g + scale_colour_grey() + guides(colour = guide_legend(override.aes = 
   list(colour='black')

事实上,我什至不确定如何访问第二个图例的任何元素。这个

g + scale_colour_grey(guide=guide_legend(title="Title", order=2)) 

只是将第一个图例的标题更改为“标题”;同样,

g + scale_colour_grey() + 
  guides(colour=guide_legend(override.aes=list(colour='black'), order=2))

覆盖cut 但不覆盖color,无论order 的值如何(或者即使省略)。

我错过了什么?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    你已经非常接近了!这里有帮助的只是将guides() 中的参数名称更改为您要更改的功能的名称,即linetype

    g + guides(linetype = guide_legend(title = "Variable: cut",  # changes the second legend
                                       override.aes = list(colour = "black")), 
               color = guide_legend(title = "Variable: color"))  # changes the first legend
    

    【讨论】:

    • 天啊!这样就可以了。虽然我觉得逻辑有点不透明。无论如何,这似乎只会影响第一个图例:与g + scale_colour_grey()+ guides(colour = guide_legend(override.aes = list(linetype='dashed'))) 比较
    • 不完全确定您在这里的意思(我不是母语人士),但我想您是对的:每个带有图例的功能在 guides() 中都有自己的参数。是的,这个表达式似乎有点长,因为它带来的少量变化。
    • 我想我想知道访问第二个、第三个...图例元素的更通用策略是什么。例如,您将如何更改 cut 的标题?也许这需要一个单独的问题?
    • 在这种特殊情况下,它不会以同样的方式工作吗? cut 是变量的名称,但有问题的特征是 linetype - g + guides(linetype = guide_legend(title ="new title", override.aes = list(colour='black')))。还是我误会了? gridgridExtra 和其他软件包可以帮助更改核心级别的 ggplot2 绘图(但我不确定您是否需要这里)。
    • 欢迎接受我的帖子,您认为它回答了您的问题。
    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多