【问题标题】:Add legend for stroke points ggplot2添加描边点ggplot2的图例
【发布时间】:2019-10-08 16:23:58
【问题描述】:

我想为图表中的笔画粗细添加一个图例。 你知道我该怎么做吗? 我可以为尺寸添加图例,但我不能为笔画添加图例。

sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2)
ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) +
  geom_abline(slope = -1, intercept = 6, colour = "white", size = 6) + 
  geom_point(shape = 21, fill = "red") + 
  scale_size(range=c(2,12), breaks=c(0,01,02),
             labels=c(">=0",">=0.1",">=0.2"), guide="legend")

【问题讨论】:

  • 请提供您的数据(dput(data) 的输出)和您的完整代码!
  • 数据很好,但我们肯定需要完整的情节代码...
  • 对不起。我忘了给你完整的代码。 ``` ggplot(大小,aes(大小,中风,大小=大小,中风=中风))+ geom_abline(斜率= -1,截距= 6,颜色=“白色”,大小= 6)+ geom_point(形状= 21 , fill = "red") + scale_size(range=c(2,12),breaks=c(0,1,2),labels=c(">=0",">=1",">=2 "),guide="legend") ```
  • HermiPara,您能否确认我从您的评论中复制到您的问题中的代码? (cmets 中的代码是可以的,大代码不是,所以当没有格式化为代码时......另外,由于 cmets 可以被跳过和/或隐藏,通常最好保持整个问题。)

标签: r ggplot2 size legend stroke


【解决方案1】:

我不认为有一个开箱即用的笔画功能,但您当然可以构建自己的。

sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2)
ggplot(sizes, aes(size, stroke, size = size, stroke = stroke)) +
  geom_abline(slope = -1, intercept = 6, colour = "white", size = 6) + 
  geom_point(shape = 21, fill = "red") + 
  scale_size(range=c(2,12), breaks=c(0,01,02),
             labels=c(">=0",">=0.1",">=0.2"), guide="legend") +
  continuous_scale("stroke", "stroke", 
                   palette = function(x){scales::rescale(x, c(0, 6))},
                   breaks = c(0, 2, 4, 6))

编辑:

我刚刚发现了scales::rescale_pal,这可能比为连续规模制作一个临时匿名函数更优雅。

continuous_scale("stroke", "stroke", 
                 palette = scales::rescale_pal(c(0, 6)),
                 breaks = c(0, 2, 4, 6))

【讨论】:

  • 这正是我所需要的。谢谢你:)
【解决方案2】:

@teunbrand 的回答肯定是更优雅的方式。
但是,当再次查看您的问题时,刚刚提出了另一种解决方法,该解决方法使用附加图层创建另一个参考线,然后手动调整该参考线以重新采样笔画宽度。
请注意,您可以使用theme(legend.key.size=unit(2, 'lines')) 使图例适合您的笔划大小。

sizes <- expand.grid(size = (0:3) * 2, stroke = (0:3) * 2)
ggplot(aes(x=size, y=stroke, size = size, stroke = stroke, color=factor(stroke)), data=sizes) + 
  geom_abline(slope = -1, intercept = 6, colour = "white", size = 6) + 
  geom_point(shape = 21, fill = "red") + # to create one layer that builds a legend for 'color'
  geom_point(shape = 21, fill = "red", color='black') + 
  theme(legend.key.size=unit(2, 'lines')) +
  scale_size(range=c(2,12),breaks=c(0,1,2),labels=c(">=0",">=1",">=2"),guide='legend') +
  guides(color=guide_legend(override.aes = list(stroke=c(0, 2, 4, 6), color='black'), title='stroke')) # fix the color guide to show stroke width


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    相关资源
    最近更新 更多