假設我有這個資料框:
# packages
library(ggplot2)
library(dplyr)
# data
genes <- c("gene1", "gene2", "gene2")
tissue <- c("Blood", "Nerve", "Brain")
pval <- c(0.8, 0.6, 0.005)
df <- data.frame(col_x = tissue,
col_y = genes,
p = pval)
我在圖中創建了一列用于標記目的:
df <- df %>%
mutate(`Post. Prob.` = ifelse(`p`>= 0.5, "P > 0.5",
ifelse(`p`>= 0.01 & `p`<= 0.5, "P > 0.01","Not sig")))
其余代碼用于情節中的不同美學。
# black ring if P>0.5
# gray ring if between 0.01 and 0.5
# white ring if not sig
ring_df <- df %>%
select(`Post. Prob.`) %>%
mutate(`ring` = ifelse(`Post. Prob.` == "P > 0.5", "black",
ifelse(`Post. Prob.` == "P > 0.01", "gray", "white")))
rings <- ring_df$ring
names(rings) <- ring_df$`Post. Prob.`
現在我創建情節:
ggplot(df)
geom_point(aes(x=`col_x`, y=`col_y`,
size=`p`,
color=`Post. Prob.`),
shape=21, # so I can fill and change the border color
fill="#6565ff", # light blue
stroke = ifelse(df$`Post. Prob.` == "P > 0.5",2, # stroke is the thickness of the border
ifelse(df$`Post. Prob.` == "P > 0.01", 2, 0.5)))
scale_color_manual(values=rings,
breaks=c("P > 0.5", "P > 0.01", "Not Sig."),
labels=c("P > 0.5", "P > 0.01", "Not Sig."),
name="Post. Prob.")
scale_size(range=c(5,10))
xlab("tissue")
ylab("genes")
但是,我的問題是,在圖例中,該圖僅顯示 P > 0.5。我知道沒有任何點遵循其他引數,但我如何制作它以便顯示灰色圖例標記?

uj5u.com熱心網友回復:
實作您想要的結果的一種選擇是
- 將您的 post prob 列轉換為具有適當級別的因子
- 設定
drop=FALSE和limits=force內部scale_color_manual以避免未使用的因子水平被丟棄
筆記:
- 而不是使用嵌套,
ifelse我建議切換到case_when. - 無需將每個列名都包裹在反引號中。僅當您使用笨拙的列名(包括空格)時才需要反引號。
- 我建議避免使用包含空格的列名,
Post. Prob.因為有更簡單的方法來獲得漂亮的標簽,例如使用labs()
library(ggplot2)
library(dplyr)
genes <- c("gene1", "gene2", "gene2")
tissue <- c("Blood", "Nerve", "Brain")
pval <- c(0.8, 0.6, 0.005)
df <- data.frame(
col_x = tissue,
col_y = genes,
p = pval
)
df <- df %>%
mutate(post_prob = case_when(
p >= 0.5 ~ "P > 0.5",
p >= 0.01 & p <= 0.5 ~ "P > 0.01",
TRUE ~ "Not sig"),
post_prob = factor(post_prob, levels = c("P > 0.5", "P > 0.01", "Not sig"))
)
rings <- df %>%
select(post_prob) %>%
mutate(ring = case_when(
post_prob == "P > 0.5" ~ "black",
post_prob == "P > 0.01" ~ "gray",
TRUE ~ "white")
) %>%
tibble::deframe()
ggplot(df)
geom_point(aes(
x = col_x, y = col_y,
size = p,
color = post_prob,
stroke = case_when(
post_prob == "P > 0.5" ~ 2,
post_prob == "P > 0.01" ~ 2,
TRUE ~ 0.5
)
),
shape = 21,
fill = "#6565ff"
)
scale_color_manual(
values = rings,
name = "Post. Prob.",
drop = FALSE,
limits = force
)
scale_size(range = c(5, 10))
xlab("tissue")
ylab("genes")

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