programing

빈도/값을 기준으로 이산형 x 척도 정렬

elecom 2023. 7. 2. 19:03
반응형

빈도/값을 기준으로 이산형 x 척도 정렬

이산형 x 척도를 가진 ggplot을 사용하여 회피 막대 차트를 만들고 있습니다. x축은 이제 알파벳 순서로 정렬되었지만 y축 값에 따라 정렬되도록 다시 정렬해야 합니다(즉, 가장 높은 막대가 왼쪽에 배치됨).

저는 순서나 정렬을 시도했지만, x축은 각각 정렬되지 않고 막대는 정렬되지 않았습니다.

제가 무엇을 잘못했지요?

나에게 가장 좋은 방법은 카테고리가 있는 벡터를 사용하는 것이었습니다.limits에 대한 매개 변수.scale_x_discrete저는 그것이 꽤 간단하고 간단한 해결책이라고 생각합니다.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

요인의 수준을 X 축에서 수동으로 설정해 보십시오.예:

library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    

ggplot of the cars dataset with factor levels automatically determined

# Manual levels
cyl_table <- table(mtcars$cyl)
cyl_levels <- names(cyl_table)[order(cyl_table)]
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels)
# Just to be clear, the above line is no different than:
# mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8"))
# You can manually set the levels in whatever order you please. 
ggplot(mtcars, aes(cyl2)) + geom_bar()

ggplot of the cars dataset with factor levels reordered manually

제임스가 답변에서 지적했듯이 요인 수준을 재정렬하는 관용적인 방법입니다.

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()

ggplot of the cars dataset with factor levels reordered using the reorder function

사용할 수 있습니다.reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")

편집:

왼쪽에서 가장 높은 막대를 사용하려면 약간의 둔기를 사용해야 합니다.

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")

저는 이것도 음의 높이를 가질 것으로 예상하지만, 그렇지 않습니다, 그래서 효과가 있습니다!

해들리는 다음과 같은 패키지를 개발해 왔습니다.forcats이 패키지를 사용하면 작업이 훨씬 쉬워집니다.악용할 수 있습니다.fct_infreq()요인의 빈도로 x축 순서를 변경하려는 경우.의 경우에는mtcars이 게시물의 예제, 당신은 레벨을 다시 정렬하고 싶습니다.cyl각 레벨의 빈도로가장 자주 나타나는 수준은 왼쪽에 있습니다.필요한 것은fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")

반대로 가고 싶다면, 당신은 사용할 수 있습니다.fct_rev()와 함께fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 

enter image description here

오래된 기능이라는 것은 알지만, 제가 만든 이 기능은 누군가에게 유용할 수도 있습니다.

order_axis<-function(data, axis, column)
{
  # for interactivity with ggplot2
  arguments <- as.list(match.call())
  col <- eval(arguments$column, data)
  ax <- eval(arguments$axis, data)

  # evaluated factors
  a<-reorder(with(data, ax), 
             with(data, col))

  #new_data
  df<-cbind.data.frame(data)
  # define new var
  within(df, 
         do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a)))
}

이제 이 함수를 사용하여 다음과 같이 ggplot2를 사용하여 대화형으로 그림을 그릴 수 있습니다.

ggplot(order_axis(df, AXIS_X, COLUMN_Y), 
       aes(x = AXIS_X_o, y = COLUMN_Y)) +
        geom_bar(stat = "identity")

보다시피,order_axisfunction은 이름이 같으나 다음과 같은 새 열을 가진 또 다른 데이터 프레임을 만듭니다._o마지막에이 새 열에는 오름차순으로 수준이 있으므로 ggplot2는 자동으로 해당 순서로 그림을 표시합니다.

이것은 다소 제한적이지만(문자 또는 요인과 열의 숫자 조합 및 오름차순으로만 작동함) 이동 중에 표시하는 데는 여전히 매우 유용합니다.

@유리 페트로브스키의 대답은 여러분이 미리 계획하고 싶은 수준을 알고 있다면 훌륭합니다.그렇지 않은 경우(예: 데이터에 없는 수준을 표시하지 않으려는 경우), 순서를 지정하는 대신 함수를 사용하는 것이 좋습니다.

library(ggplot2)

my_order <- as.character(c(8,3,4,5,6))    # the `as.character` calls are only
ggplot(mtcars, aes(as.character(cyl))) +  # necessary for the OP's example
  geom_bar() +
  scale_x_discrete(limits = function(x) my_order[my_order %in% x])

에의 에서.scale_x_discrete:

limits
다음 중 하나:
을 사용하려면 NULL을 합니다.
과 그 를
       값을 입니다.

그렇지 않으면 그래프가 다음과 같이 됩니다(더 좋을 수 있음).

ggplot(mtcars, aes(as.character(cyl))) +
  geom_bar() +
  scale_x_discrete(limits = my_order)

할 수 . X축은 X축과 같은 순서로 설정할 수 있습니다.fct_relevelforcats)tidyverse가 가장 합니다. @jazzurro는 @jazzazzurro는 @jazzzurro는 를 사용합니다fct_infreq (으로부터)forcats).

library(tidyverse)

ggplot(iris, aes(
  x = fct_relevel(Species, 'virginica', 'versicolor', 'setosa'),
  y = Petal.Width)) +
  geom_col() +
  xlab("Species") +
  ylab("Petal Width") +
  theme_bw()

산출량

enter image description here

만 사용할 수 있습니다.fct_relevel東京의 ggplot신청만 하면 됩니다.factor에 먼저에 변로먼이다사음용니다합한동저수다사▁to▁first니합을 사용합니다.fct_relevel.

ggplot(mtcars, aes(fct_relevel(factor(cyl), "6", "8", "4"))) +
  geom_bar() +
  labs(x = "cyl")

산출량

enter image description here

언급URL : https://stackoverflow.com/questions/3253641/order-discrete-x-scale-by-frequency-value

반응형