如何在ggpairs()中添加外部图例? [英] How to add an external legend to ggpairs()?

查看:333
本文介绍了如何在ggpairs()中添加外部图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ggpairs绘制散点图矩阵.我正在使用以下代码:

I am plotting a scatterplot matrix using ggpairs. I am using the following code:

# Load required packages
require(GGally)

# Load datasets
data(state)
df <- data.frame(state.x77,
                 State = state.name,
                 Abbrev = state.abb,
                 Region = state.region,
                 Division = state.division
) 
# Create scatterplot matrix
p <- ggpairs(df, 
             # Columns to include in the matrix
             columns = c(3,5,6,7),

             # What to include above diagonal
             # list(continuous = "points") to mirror
             # "blank" to turn off
             upper = "blank",
             legends=T,

             # What to include below diagonal
             lower = list(continuous = "points"),

             # What to include in the diagonal
             diag = list(continuous = "density"),

             # How to label inner plots
             # internal, none, show
             axisLabels = "none",

             # Other aes() parameters
             colour = "Region",
             title = "State Scatterplot Matrix"
) 

# Show the plot
print(p)

我得到以下情节:

现在,您可以轻松地看到我正在为矩阵中的每个图获取图例.我只想为整个情节准备一个通用的图例.我怎么做? 任何帮助将不胜感激.

Now, one can easily see that I am getting legends for every plot in the matrix. I would like to have ONLY ONE universal legend for the whole plot. How do I do that? Any help would be much appreciated.

推荐答案

我正在研究类似的东西,这就是我要采用的方法,

I am working on something similar, this is the approach i would take,

  1. 确保在ggpairs函数调用中将图例设置为"TRUE"
  2. 现在遍历图矩阵中的子图,并删除每个图例的图例,仅保留其中一个图例,因为所有密度均绘制在同一列上.

  1. Ensure legends are set to 'TRUE' in the ggpairs function call
  2. Now iterate over the subplots in the plot matrix and remove the legends for each of them and just retain one of them since the densities are all plotted on the same column.

colIdx <- c(3,5,6,7)

for (i in 1:length(colIdx)) {

  # Address only the diagonal elements
  # Get plot out of matrix
  inner <- getPlot(p, i, i);

  # Add any ggplot2 settings you want (blank grid here)
  inner <- inner + theme(panel.grid = element_blank()) +
    theme(axis.text.x = element_blank())

  # Put it back into the matrix
  p <- putPlot(p, inner, i, i)

  for (j in 1:length(colIdx)){
    if((i==1 & j==1)){

      # Move legend right
      inner <- getPlot(p, i, j)
      inner <- inner + theme(legend.position=c(length(colIdx)-0.25,0.50)) 
      p <- putPlot(p, inner, i, j)
    }
    else{

      # Delete legend
      inner <- getPlot(p, i, j)
      inner <- inner + theme(legend.position="none")
      p <- putPlot(p, inner, i, j)
    }
  }
}

这篇关于如何在ggpairs()中添加外部图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆