geom_rect和图例,显示矩形的宽度

时间:2015-07-17 14:54:51

标签: r ggplot2

这是一个非常简单的脚本

library(ggplot2)

df <- data.frame(xmin = c(1, 2.5, 3), xmax = c(2, 3.5, 5), ymin=c(1,1.5, 3), ymax = c(2,2.5,4), size = c(1,1,2), fill = c("red", "orange", "blue"))

p <- ggplot()
p <- p + geom_rect(data = df, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, size = factor(size), fill = fill))
p <- p + scale_size_manual(values = c(1,2), guide = guide_legend(keywidth = 4, override.aes = list(colour = "black")))

p

此脚本创建以下图表...

enter image description here

我想要实现的目标是添加一个反映矩形宽度的图例(指南)!只有2个简单的行作为&#34;传奇键&#34;而键的宽度为1或2。

我被卡住了,所以任何提示都很受欢迎

1 个答案:

答案 0 :(得分:0)

由于您指定了xmin / xmax和ymin / ymax,我认为size参数在这里没有做任何事情

my_dat <- data.frame(xmin = c(1, 2.5, 3), xmax = c(2, 3.5, 5), 
                     ymin=c(1,1.5, 3), ymax = c(2,2.5,4), 
                     size = c(1,1,2), fill = c("red", "orange", "blue"))

# size doesn't do anything for geom_rect. compare this...
ggplot(my_dat) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, 
                size = factor(size), fill = fill))

# ...and this. same!
ggplot(my_dat) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, 
                fill = fill))

# try geom_linerange

ggplot(my_dat) +
  geom_linerange(aes(x=(xmin+xmax)/2, ymin=ymin, ymax=ymax, color=fill, 
                     size=factor(size))) +
  scale_size_manual(values=c(20, 50)) +
  xlim(1, 5)

enter image description here

编辑使结果更接近原始情节,尽管这是一个古怪的情节调用。

如果您添加+ theme(legend.direction = 'horizontal')

enter image description here