【问题标题】:ggplot - a custom legendggplot - 自定义图例
【发布时间】:2014-08-26 23:42:06
【问题描述】:

我想在 ggplot2 中绘制一个自定义图例。我尝试过,正如这里关于类似主题的其他问题所建议的那样,scale_colour_manualguide=legend 等,但到目前为止默认图例是不可移动的。默认图例忽略两个图,并不必要地为第三个图绘制大小级别。我想要一个这样的传奇:

[浅灰色线]图1
[黑色圆圈大小=1] 图2
[大小为 1 的灰色矩形] 图 3

这里是代码,带有示例数据框。自定义图例修改(例如来自 this question 的这些修改)似乎没有任何作用。

cloud2 <- data.frame(x = c(0, 1, 2), y = c(0.3, 0.4, 0.5))
sandwich3 <- data.frame(x = c(1, 2, 3), y = c(0.4, 0.5, 0.6), p = c(0.1, 0.6, 0.3))
sandwich4 <- data.frame(x = c(3, 4, 5), y = c(0.6, 0.3, 0.5), p = c(0.1, 0.7, 0.2))
ggplot(cloud2, aes(x=x, y=y)) + geom_line(size=0.1,colour="gray70") +
  aes(x=x, y=y, size=sqrt(p)) +
  geom_point(data=sandwich3,colour="gray40",shape=15) + scale_size(range=c(0,2)) +
  geom_point(data=sandwich4,colour="black",shape=16) +
  theme(legend.position=c(0.905, 0.14), legend.title=element_blank(),
  axis.ticks = element_line(colour = "black"), axis.text = element_text(colour = "black")) +
  scale_x_continuous(limits = c(-5, 5), breaks=c(-2, 0, 2)) +
  scale_y_continuous(limits = c(-1.1, 1.2))

结果图,使用原始数据框:

【问题讨论】:

  • 你介意提供一个可重现的例子吗?
  • 很多时候这只是关于以正确的方式格式化数据。然后ggplot会自动生成图例。确保您的数据格式正确,无需查看就无法更具体...
  • 除了@konvas,我认为你需要将你的数据重塑为长格式,例如reshape2包。正如您目前所说的那样,很难说出您做错了什么。提供您的(部分)数据的dput 将使我们更容易为您提供帮助。
  • 我添加了一个工作示例。我只将 R 用于图表,而且我对它的了解很少。数据只是三帧。

标签: r ggplot2 legend


【解决方案1】:

首先,最好将所有数据保存在一个位置。我使用rbind 制作了一个带有几个额外列的数据框。这样,映射到aes 也更简单,因为它在所有几何对象中声明一次:

df_plot
  x   y   p series line
1 0 0.3  NA      1    1
2 1 0.4  NA      1    1
3 2 0.5  NA      1    1
4 1 0.4 0.1      2    2
5 2 0.5 0.6      2    2
6 3 0.6 0.3      2    2
7 3 0.6 0.1      3    2
8 4 0.3 0.7      3    2
9 5 0.5 0.2      3    2

注意因素的使用:

str(df_plot)
'data.frame':   9 obs. of  5 variables:
 $ x     : num  0 1 2 1 2 3 3 4 5
 $ y     : num  0.3 0.4 0.5 0.4 0.5 0.6 0.6 0.3 0.5
 $ p     : num  NA NA NA 0.1 0.6 0.3 0.1 0.7 0.2
 $ series: Factor w/ 3 levels "1","2","3": 1 1 1 2 2 2 3 3 3
 $ line  : Factor w/ 2 levels "1","2": 1 1 1 2 2 2 2 2 2

现在,只需准确映射并覆盖所有比例:

ggplot(df_plot, aes(x = x, y = y, size = sqrt(p), 
                    linetype = series, shape = series, colour = series)) + 
    geom_line(size = 0.1) + 
    geom_point() + 
    scale_x_continuous(limits = c(-5, 5), breaks=c(-2, 0, 2)) +
    scale_y_continuous(limits = c(-1.1, 1.2)) +
    scale_shape_manual(values = c(NA, 15, 16)) + 
    scale_linetype_manual(values = c(1, 0, 0)) +
    scale_colour_manual(values = c("gray70", "gray40", "black")) + 
    scale_size(range = c(0,2)) +
    theme(legend.position = c(0.905, 0.14), legend.title = element_blank(),
          axis.ticks = element_line(colour = "black"), 
          axis.text = element_text(colour = "black")) +
    guides(size = F)

这样一来,您的初始图片就没有改变,但图例(自动)是正确的:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2020-07-28
    • 2018-09-15
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多