我正在處理以數字結尾的字串,并希望將字串按數字順序排列以用于圖形圖例。
# Example dataframe
d <- data.frame(
SampleID = sprintf("sample_%s", rep(10:39)),
Variable = 1:30,
Group = append(rep("group_1", each = 15), rep("group_2", each = 15)),
Group1 = runif(30, min=0, max=100),
Group2 = runif(30, min=0, max=100)
)
# Character level I add to give each animal unique shape
d$Animals <- sprintf("Animal_%s",rep(c(1:10), each = 3))
library(ggplot2)
# Plot
ggplot(d, aes(Group1, Group2, color=Group, shape=Animals))
xlab(paste0("Value 1"))
ylab(paste0("Value 2"))
coord_fixed()
geom_point()
scale_shape_manual(values=c(0:10))
我目前的輸出是這個

uj5u.com熱心網友回復:
您可以將 Animal 變數轉換為有序和水平因子
# Example dataframe
d <- data.frame(
SampleID = sprintf("sample_%s", rep(10:39)),
Variable = 1:30,
Group = append(rep("group_1", each = 15), rep("group_2", each = 15)),
Group1 = runif(30, min=0, max=100),
Group2 = runif(30, min=0, max=100)
)
# Character level I add to give each animal unique shape
d$Animals <- sprintf("Animal_%s",rep(c(1:10), each = 3))
d <- d %>%
mutate(Animals = factor(Animals,
levels = c( "Animal_1" , "Animal_2" , "Animal_3" , "Animal_4", "Animal_5" ,
"Animal_6" , "Animal_7", "Animal_8" , "Animal_9" ,"Animal_10"),
ordered = T))
library(ggplot2)
# Plot
ggplot(d, aes(Group1, Group2, color=Group, shape=Animals))
xlab(paste0("Value 1"))
ylab(paste0("Value 2"))
coord_fixed()
geom_point()
scale_shape_manual(values=c(0:10))

uj5u.com熱心網友回復:
如果因子數量太大,則可接受的解決方案不可行,因為它需要以正確的順序手動輸入因子水平。如果原始資料的排序不正確,則建議的其他解決方案(用于unique(d$Animals)以正確的順序獲取級別)也可能會失敗。如果有人需要更通用的解決方案(這是一個非常常見的問題),您可以使用
d$Animals <- factor(sprintf("Animal_%s",rep(c(1:10), each = 3)))
d$Animals <- reorder(d$Animals,
as.numeric(gsub("^[^_]*_(\\d ).*", "\\1", d$Animals)))
這將根據在字串中找到的第一個數字正確地重新排序級別,無論是 10 還是 1000 級別以及它們在資料集中出現的順序。
uj5u.com熱心網友回復:
謝謝@Susan Switzer,我會接受這個答案,但是我對您的原始解決方案做了一些改動。
d <- data.frame(
SampleID = sprintf("sample_%s", rep(10:39)),
Variable = 1:30,
Group = append(rep("group_1", each = 15), rep("group_2", each = 15)),
Group1 = runif(30, min=0, max=100),
Group2 = runif(30, min=0, max=100)
)
d$Animals <- sprintf("Animal_%s",rep(c(1:10), each = 3))
library(dplyr)
d <- d %>%
mutate(Animals = factor(Animals,
levels = unique(d$Animals),
ordered = T))
library(ggplot2)
ggplot(d, aes(Group1, Group2, color=Group, shape=Animals))
xlab(paste0("Value 1"))
ylab(paste0("Value 2"))
coord_fixed()
geom_point()
scale_shape_manual(values=c(0:10))

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/437581.html
