首页 文章

ggplot - 一个自定义图例

提问于
浏览
2

我想在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))

结果图,使用原始数据框:
enter image description here

1 回答

  • 1

    首先,最好将所有数据保存在一个地方 . 我使用 rbind 创建了一个包含多个额外列的数据帧 . 这样,映射到 aes 也简单得多,因为它在所有geoms中声明一次:

    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)
    

    这样,您的初始图片不会受到影响,但图例(自动)正确:

    enter image description here

    enter image description here

相关问题