gpt4 book ai didi

r - 如何向 ggpairs() 添加外部图例?

转载 作者:行者123 更新时间:2023-12-04 01:49:06 24 4
gpt4 key购买 nike

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

# 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)

我得到以下情节:

enter image description here

现在,人们可以很容易地看到,我为矩阵中的每个图都得到了图例。我希望整个情节只有一个普遍的传说。我怎么做?
任何帮助将非常感激。

最佳答案

我正在做类似的事情,这是我会采取的方法,

  • 确保在 ggpairs 中将图例设置为“TRUE”函数调用
  • 现在迭代绘图矩阵中的子图并删除它们中的每一个的图例,只保留其中一个,因为密度都绘制在同一列上。
    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)
    }
    }
    }
  • 关于r - 如何向 ggpairs() 添加外部图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22945702/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com