it-source

변수를 사용하여 열 이름을 지정하는 방법 ggplot

criticalcode 2023. 6. 6. 00:00
반응형

변수를 사용하여 열 이름을 지정하는 방법 ggplot

ggplot 명령이 있습니다.

ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )

함수 내부에하지만 저는 함수의 매개 변수를 사용하여 색상과 그룹으로 사용할 열을 선택할 수 있기를 원합니다.예를 들어, 저는 이런 것을 원합니다.

f <- function( column ) {
    ...
    ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) )
}

ggplot에 사용되는 열이 모수에 의해 결정되도록 합니다.예: f("majr")의 경우 다음과 같은 효과를 얻습니다.

ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )

하지만 f("gender")의 영향을 받습니다.

  ggplot( rates.by.groups, aes(x=name, y=rate, colour=gender, group=gender) )

제가 시도한 것들:

ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ) )

작동하지 않았습니다.하지도 하지 않았습니다.

e <- environment() 
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ), environment=e )

참고: 이 답변의 솔루션은 "소프트 사용 안 함"입니다.다음을 사용하여 아래 답변 참조.data[[현재 선호하는 방법입니다.

사용할 수 있습니다.aes_string:

f <- function( column ) {
    ...
    ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column,
                                        group=column ) )
}

열을 문자열로 함수에 전달하기만 하면 됩니다.f("majr")보다는f(majr) 또한 다른 열을 변경했습니다."name"그리고."rate"현이 되는 것.

어떤 이유로든 당신이 사용하지 않는 것이 좋다면,aes_string다음으로 변경할 수 있습니다(좀 더 번거로운 경우).

    ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
                                        group=get(column) ) )

릴리스 노트에서ggplot2 V3.0.0:

aes()는 이제 준인용 부호를 지원하므로!!,!!!!, :=를 사용할 수 있습니다.이제 소프트 사용이 중단된 aes_() 및 aes_string()을 대체합니다(그러나 오랫동안 유지됨).

이제 관용적인 방법은 변수에 포함된 문자열을 기호로 변환하는 것입니다.sym()(기본 별칭과 거의 동일함)as.name()/as.symbol()), 를 사용하여 인용 취소합니다.!!

OP의 데이터를 시뮬레이션하여 우리가 할 수 있는 것은 다음과 같습니다.

library(tidyverse)
rates.by.groups <- data.frame(
  name = LETTERS[1:3],
  rate = 1:3,
  mjr = LETTERS[c(4,4,5)],
  gender = c("M","F","F")
)

f <- function(column) {
  column <- sym(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_col()
}

f("gender")
f("mjr")
x <- "gender"
f(x)

원시 이름을 함수에 입력하는 것이 좋다면 다음을 수행할 수 있습니다.

f2 <- function(column) {
  column <- ensym(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_col()
}

이름 또는 문자열 리터럴과 함께 작동합니다.

f2(gender)
f2(mjr)
f2("gender")
f2("mjr")

라이오넬이 말한 것처럼ensym():

LHS에서 둘 다 제공할 수 있는 인수의 구문을 모방하기 위한 것입니다. 예를 들어, 목록(예: "숫자 = 1, "숫자" = 2).


에 대한 주의사항enquo()

enquo()인수에 공급된 식을 인용합니다(반드시 기호는 아님). 문자열 리터럴을 다음과 같이 기호로 변환하지 않습니다.ensym()그렇게 해서 여기서는 덜 적응할 수 있지만, 우리는 할 수 있습니다.

f3 <- function(column) {
  column <- enquo(column)
  ggplot(rates.by.groups, 
         aes(x = name, 
             y = rate, 
             fill  = !!column, 
             group = !!column)) +
    geom_col()
}

f3(gender)
f2(mjr)

다른 옵션(ggplot2 > 3.0.0)는 단정한 평가 대명사를 사용하여 선택된 변수/열을 다음 중에서 잘라내는 것입니다.rates.by.groups데이터 프레임

답변 참조

library(ggplot2)
theme_set(theme_classic(base_size = 14))

# created by @Moody_Mudskipper
rates.by.groups <- data.frame(
  name = LETTERS[1:3],
  rate = 1:3,
  mjr = LETTERS[c(4, 4, 5)],
  gender = c("M", "F", "F")
)

f1 <- function(df, column) {
  gg <- ggplot(df, 
         aes(x = name, 
             y = rate, 
             fill  = .data[[column]], 
             group = .data[[column]])) +
    geom_col() +
    labs(fill = column)
  return(gg)
}

plot_list <- lapply(list("gender", "mjr"), function(x){ f1(rates.by.groups, x) })
plot_list
#> [[1]]

#> 
#> [[2]]

# combine all plots
library(egg)
ggarrange(plots = plot_list,
          nrow = 2,
          labels = c('A)', 'B)'))

reprex 패키지(v0.2.1.9000)에 의해 2019-04-04에 생성되었습니다.

사용해 보십시오.aes_string대신에aes.

두 가지 일을 하라.

  1. 열 이름을 다음과 같은 기호로 변환합니다.sym()
  2. 프레펜드!!사용하고자 할 때 기호로

my_col <- sym("Petal.Length")

iris %>% 
  ggplot(aes(x = Sepal.Length, y = !!my_col)) +
  geom_point()

사용.aes_string이 문제를 해결하지만 오류 표시줄을 추가할 때 문제가 발생합니다.geom_errorbar아래는 간단한 해결책입니다.

#Identify your variables using the names of your columns indie your dataset
 xaxis   <- "Independent"   
 yaxis   <- "Dependent"
 sd      <- "error"

#Specify error bar range (in 'a-b' not 'a'-'b')
 range   <- c(yaxis, sd)                                #using c(X, y) allows use of quotation marks inside formula
 yerrbar <- aes_string(ymin=paste(range, collapse='-'), 
                       ymax=paste(range, collapse='+'))


#Build the plot
  ggplot(data=Dataset, aes_string(x=xaxis, y=yaxis)) +
    geom_errorbar(mapping=yerrbar, width=15, colour="#73777a", size = 0.5) +
    geom_point   (shape=21)

GG 그림 내부의 다음 선을 사용하여 그림에 면을 추가할 수도 있습니다.

facet_grid(formula(paste(Variable1, "~", Variable2)))

이 스크립트는 이 원래 게시물에서 수정되었습니다. ggplot2 - 사용자 지정 함수를 사용한 오류 표시줄

언급URL : https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot

반응형