重命名列但在 R 中的 ggplot 2 中保持相同的排序

问题描述 投票:0回答:1

我有一个名为 df 的数据框,包含 2 个字符变量和一个双精度变量。

我试图解决的问题的最初问题是这个here。简而言之,我试图在每个方面从低到高对增量值进行排序,但我也想查看 y 轴中的 my_vars2 值。目前我只看到字母。我如何解决这个问题但仍然具有相同的排序从较低值到较高值?

library(ggplot2)
library(dplyr)
library(forcats)
library(stringr)

## init data --------------------------------------
set.seed(123)  # Setting seed for reproducibility
levels <- c('KAMALA-IT', 'HARRIS-HR', 'DONALD-CEO', 'TRUMP-HR', 'BARACK-IT')
my_var <- sample(levels, 50, replace = TRUE)
levels2 <- c('GEORGIA', 'PENNSYLVANIA', 'WINSCOSIN', 'NORTH CAROLINA', 'NEVADA','ARIZONA','MICHIGAN')
my_var2 <- sample(levels2, 50, replace = TRUE)
delta <- rnorm(50, mean = 0, sd = 1) 

df <- tibble(my_var,my_var2,delta);df
df <- 
  group_by(df, my_var) |> 
  arrange(delta, .by_group = TRUE) |> 
  mutate(labels = paste0(letters[1:n()], "/", my_var2))



ggplot(df, aes(x = delta, y = labels)) +
  geom_point(colour = "red") +
  
  # "free_y" lets the y axis move around between facets
  facet_wrap(~my_var, dir = "v", ncol = 1, scales = "free_y") +
  
  # Remove the ordering component of each label:
  scale_y_discrete(labels = \(x) str_extract(x, "(?<=/)."))
r dataframe ggplot2
1个回答
0
投票

只需在标签中包含州名称(又名

my_var2
)即可。

library(tidyverse)

df <-
  group_by(df, my_var) |>
  arrange(delta, .by_group = TRUE) |>
  mutate(labels = fct_inorder(paste(my_var2, my_var, delta, sep = ".")))

ggplot(df, aes(x = delta, y = labels)) +
  geom_point(colour = "red") +
  # "free_y" lets the y axis move around between facets
  facet_wrap(~my_var, dir = "v", ncol = 1, scales = "free_y") +
  # Remove the ordering component of each label:
  scale_y_discrete(labels = \(x) gsub("\\..*$", "", x)) +
  theme()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.