我有以下图表
是否可以在相应的箱形图下添加图例标签(HPD和Quantile)?我还能摆脱中间的白条吗?
我的代码如下:
p <- ggplot(Results.Baseline,aes(x=Inference, y=Results, fill=Method)) +
scale_y_continuous(limits = c(0, 1))+
geom_boxplot()+facet_wrap(~Method)+ facet_wrap(~Model)+
geom_hline(yintercept=0.95, linetype="dashed", color = "red")
Here is my data:
data <- structure(list(Results = c(0.234375, 0.203125, 0.234375, 0.203125,
0.21875, 0.203125), Model = c("Baseline 1", "Baseline 1", "Baseline 1",
"Baseline 1", "Baseline 1", "Baseline 1"), Method = c("Quantile",
"Quantile", "Quantile", "Quantile", "Quantile", "Quantile"),
Inference = c("HMDM", "HMDM", "HMDM", "HMDM", "HMDM", "HMDM"
)), .Names = c("Results", "Model", "Method", "Inference"), row.names = c("1:nrow(transitions)",
"V2", "V3", "V4", "V5", "V6"), class = "data.frame")
答案 0 :(得分:1)
我添加了更多数据,以便更好地复制您的图表。您可以 使用
geom_text
将Method
标签添加到图形中。你必须 每个箱形图只保留一个标签,这就是为什么我创建了datalabs
数据框。另外,您的绘图中不需要两个facet_wraps
。是否 这可以帮助您回答问题吗?
data <- structure(list(Results = c(0.234375, 0.203125, 0.234375, 0.203125,
0.21875, 0.203125), Model = c("Baseline 1", "Baseline 1", "Baseline
1",
"Baseline 1", "Baseline 1", "Baseline 1"), Method = c("Quantile",
"Quantile", "Quantile", "Quantile", "Quantile", "Quantile"),
Inference = c("HMDM", "HMDM", "HMDM", "HMDM", "HMDM", "HMDM"
)), .Names = c("Results", "Model", "Method", "Inference"), row.names = c("1:nrow(transitions)",
"V2", "V3", "V4", "V5", "V6"), class = "data.frame")
data2 <- structure(list(Results = c(0.234375, 0.203125, 0.234375, 0.203125,
0.21875, 0.203125), Model = c("Baseline 2", "Baseline 2", "Baseline 2",
"Baseline 2", "Baseline 2", "Baseline 2"), Method = c("HPD",
"HPD", "HPD", "HPD", "HPD", "HPD"),
Inference = c("Eco. Inf.", "Eco. Inf.", "Eco. Inf.", "Eco. Inf.",
"Eco. Inf.", "Eco. Inf."
)), .Names = c("Results", "Model", "Method", "Inference"), row.names = c("1:nrow(transitions)",
"V2", "V3", "V4", "V5", "V6"), class = "data.frame")
data3 <- rbind(data,data2)
data4 <- mutate(data3, Method = ifelse(Method == "Quantile",
"HPD","Quantile"),
Inference = ifelse(Inference == "HMDM","Eco. Inf.",
"HMDM"))
data5 <- rbind(data3,data4)
datalabs <- data5 %>%
group_by(Method,Model) %>%
arrange(Method,Model) %>%
filter(row_number()==1)
ggplot(data5,aes(x=Inference, y=Results, fill=Method)) +
scale_y_continuous(limits = c(0, 1))+
geom_boxplot()+
facet_wrap(~Model)+
geom_hline(yintercept=0.95, linetype="dashed", color = "red")+
geom_text(data = datalabs, aes(label=Method) ,
nudge_y = -.1)+
theme_bw() +
theme(panel.grid = element_blank()) +
theme(panel.spacing = unit(0, "lines"),
strip.background = element_blank(),
panel.border = element_rect(fill = NA, color="white"))