R-ggplot2:在图例中插入子标题

时间:2018-11-19 14:34:46

标签: r ggplot2 legend

我正在制作一个带有ggplot2的地图,该地图的颜色代表六种类型的区域,可以将其进一步分为三类。

使用

  

scale_fill_manual(labels = MyLabels,值= MyColors)

我可以得到一个简单的图例,其中显示了6个区域:

enter image description here

但是出于出版目的,我想得到的是:

enter image description here

理想,主要类别包括在图例中作为子标题。

那怎么可行?

1 个答案:

答案 0 :(得分:3)

您可以尝试在数据中添加伪行,并使用这些伪行创建子标题。

有一个带有假值的样本数据:

$ DEBUG=keystone:fields:file node keystone.js

------------------------------------------------
KeystoneJS v4.0.0 started:
keystone-s3 is ready on http://0.0.0.0:3000
------------------------------------------------

GET /keystone/images/5bf2c27e05ba79178cd7d2be 200 17.446 ms
GET /keystone/api/images/5bf2c27e05ba79178cd7d2be?drilldown=true 304 3.528 ms
  keystone:fields:file [Image.file] Validating input:  upload:File-file-1001 +0ms
  keystone:fields:file [Image.file] Validation result:  true +1ms
  keystone:fields:file [Image.file] Uploading file for item 5bf2c27e05ba79178cd7d2be: { fieldname: 'File-file-1001',
  originalname: 'oof.PNG',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'C:\\Users\\Dylan\\AppData\\Local\\Temp',
  filename: '42c161c1c36a84a244a2cf09d327afd4',
  path:
   'C:\\Users\\Dylan\\AppData\\Local\\Temp\\42c161c1c36a84a244a2cf09d327afd4',
  size: 6684 } +0ms
POST /keystone/api/images/5bf2c27e05ba79178cd7d2be 500 225.027 ms

现在,我创建设置标签和颜色以在df <- data.frame(x = 1:9, y = c(0, 0, 0, rnorm(6)), g = factor(c("fakedog", "bigdog", "smalldog", "fakerabbit", "rabbit", "fakecat", "white", "black", "gray"))) 中使用:

ggplot

并绘制示例数据:

lbl <- c(expression(bold("dogs")), "big dogs", "small dogs",
         expression(bold("rabbits")), "rabbits",
         expression(bold("cats")), "white", "black", "gray")
colo <- c(NA, "red1", "red3",
          NA, "blue1", 
          NA, "green1", "green2", "green3")

最终输出:

enter image description here