두 개의 범례가 포함 된 ggplot2에 의해 생성 된 플롯이 있습니다. 전설을 배치하는 은 이상적이 아니므로 을 조정하고 싶습니다. 나는 the answer to "How do I position two legends independently in ggplot"에 나와있는 방법을 모방하려고 노력했다. 해당 답변에 표시된 예가 작동합니다. 그러나, 나는 내 상황에서 작동하도록 설명한 방법을 얻을 수 없습니다.면 처리 된 ggplot2 플롯에 독립적으로 두 범례 배치
데비안 압착에서 R 2.15.3 (2013-03-01), ggplot2_0.9.3.1, lattice_0.20-13, gtable_0.1.2, gridExtra_0.9.1 을 사용하고 있습니다.
minimal.R
에 의해 생성 된 플롯을 고려하십시오. 이것은 내 실제 플롯 인 과 유사합니다.
########################
minimal.R
########################
get_stat <- function()
{
n = 20
q1 = qnorm(seq(3, 17)/20, 14, 5)
q2 = qnorm(seq(1, 19)/20, 65, 10)
Stat = data.frame(value = c(q1, q2),
pvalue = c(dnorm(q1, 14, 5)/max(dnorm(q1, 14, 5)), d = dnorm(q2, 65, 10)/max(dnorm(q2, 65, 10))),
variable = c(rep('true', length(q1)), rep('data', length(q2))))
return(Stat)
}
stat_all<- function()
{
library(ggplot2)
library(gridExtra)
stathuman = get_stat()
stathuman$dataset = "human"
statmouse = get_stat()
statmouse$dataset = "mouse"
stat = merge(stathuman, statmouse, all=TRUE)
return(stat)
}
simplot <- function()
{
Stat = stat_all()
Pvalue = subset(Stat, variable=="true")
pdf(file = "CDF.pdf", width = 5.5, height = 2.7)
stat = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
scale_x_continuous("Negative log likelihood") +
scale_y_continuous("Proportion $<$ x") +
facet_grid(~ dataset, scales='free') +
scale_colour_manual(values = c("blue", "red"), name="Data type",
labels=c("Gene segments", "Model"), guide=guide_legend(override.aes = list(size = 2))) +
geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""))
print(stat)
dev.off()
}
simplot()
이 결과는 다음 그림과 같습니다. 보시다시피, Data type
및 Pvalue
범례는 잘 배치되지 않았습니다. 이 코드를 minimal2.R
으로 수정했습니다. 상단에 범례를 두어야 버전 1로
이 코드는 오류없이 실행,하지만 전설은 표시되지 않습니다.
편집 : 두 개의 상자가 하나씩 표시됩니다. 맨 위의 은 비어 있습니다. grid.arrange()
에 높이를 설정하지 않은 경우 @baptiste에 의해 작성된대로 범례와 플롯이 모두 아래 상자에 배치됩니다. 높이를 그림과 같이 설정하면 범례가 표시되지 않습니다.
EDIT2 : 앞의 질문에서 복사 한 grid.newpage
, 에 의해 여분의 빈 상자가 호출 된 것 같습니다. 왜 거기에 있었는지 나는 모르겠다. 그 행을 사용하지 않으면 상자/페이지가 하나만 나타납니다.
버전 2에서는이 오류가 발생합니다.
Error in UseMethod("grid.draw") :
no applicable method for 'grid.draw' applied to an object of class "c('gg', 'ggplot')"
Calls: simplot -> grid.draw
편집 : @baptiste에 의해 제안 내가 print(plotNew)
를 사용하는 경우, 내가 여기에 무슨 일이 일어나고 있는지 알아 내려고 노력
Error in if (empty(data)) { : missing value where TRUE/FALSE needed
Calls: simplot ... facet_map_layout -> facet_map_layout.grid -> locate_grid.
다음과 같은 오류를 얻을,하지만 난 많은 를 찾을 수 없습니다 관련 정보.
참고 :
나는 내가 경험 CDF의 계단 효과를 얻고있다 이유를 모르겠어요. 확실한 설명이있을 것입니다. 알고 계신다면 나를 가르치십시오.
나는이 코드의 대안을 고려할 의향이 있으며 누구나 대안을 제안 할 수 있다면 예 : 이 그래프를 작성하는 ggplot2조차도 고려해야합니다. matplotlib, 나는 결코 심각하게 실험하지 않았다.
minimal2.R
에추가
print(ggplot_gtable(ggplot_build(stat2)))
나에게
TableGrob (7 x 7) "layout": 12 grobs z cells name grob 1 0 (1-7,1-7) background rect[plot.background.rect.186] 2 1 (3-3,4-4) strip-top absoluteGrob[strip.absoluteGrob.135] 3 2 (3-3,6-6) strip-top absoluteGrob[strip.absoluteGrob.141] 4 5 (4-4,3-3) axis-l absoluteGrob[GRID.absoluteGrob.129] 5 3 (4-4,4-4) panel gTree[GRID.gTree.155] 6 4 (4-4,6-6) panel gTree[GRID.gTree.169] 7 6 (5-5,4-4) axis-b absoluteGrob[GRID.absoluteGrob.117] 8 7 (5-5,6-6) axis-b absoluteGrob[GRID.absoluteGrob.123] 9 8 (6-6,4-6) xlab text[axis.title.x.text.171] 10 9 (4-4,2-2) ylab text[axis.title.y.text.173] 11 10 (4-4,4-6) guide-box gtable[guide-box] 12 11 (2-2,4-6) title text[plot.title.text.184]
나는이 고장을 이해하지 못하고 있습니다. 아무도 설명 할 수 있을까요?
guide-box
은 범례에 해당하며, 어떻게 알 수 있습니까?
여기 내 코드의 수정 된 버전은 minimal2.R
입니다.
########################
minimal2.R
########################
get_stat <- function()
{
n = 20
q1 = qnorm(seq(3, 17)/20, 14, 5)
q2 = qnorm(seq(1, 19)/20, 65, 10)
Stat = data.frame(value = c(q1, q2),
pvalue = c(dnorm(q1, 14, 5)/max(dnorm(q1, 14, 5)), d = dnorm(q2, 65, 10)/max(dnorm(q2, 65, 10))),
variable = c(rep('true', length(q1)), rep('data', length(q2))))
return(Stat)
}
stat_all<- function()
{
library(ggplot2)
library(gridExtra)
library(gtable)
stathuman = get_stat()
stathuman$dataset = "human"
statmouse = get_stat()
statmouse$dataset = "mouse"
stat = merge(stathuman, statmouse, all=TRUE)
return(stat)
}
simplot <- function()
{
Stat = stat_all()
Pvalue = subset(Stat, variable=="true")
pdf(file = "CDF.pdf", width = 5.5, height = 2.7)
## only include data type legend
stat1 = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
scale_x_continuous("Negative log likelihood") +
scale_y_continuous("Proportion $<$ x") +
facet_grid(~ dataset, scales='free') +
scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=guide_legend(override.aes = list(size = 2))) +
geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""), guide=FALSE)
## Extract data type legend
dataleg <- gtable_filter(ggplot_gtable(ggplot_build(stat1)), "guide-box")
## only include pvalue legend
stat2 = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
scale_x_continuous("Negative log likelihood") +
scale_y_continuous("Proportion $<$ x") +
facet_grid(~ dataset, scales='free') +
scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=FALSE) +
geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""))
## Extract pvalue legend
pvalleg <- gtable_filter(ggplot_gtable(ggplot_build(stat2)), "guide-box")
## no legends
stat = ggplot() + stat_ecdf(data=Stat, n=1000, aes(x=value, colour = variable)) +
theme(legend.key = element_blank(), legend.background = element_blank(), legend.position=c(.9, .25), legend.title = element_text(face = "bold")) +
scale_x_continuous("Negative log likelihood") +
scale_y_continuous("Proportion $<$ x") +
facet_grid(~ dataset, scales='free') +
scale_colour_manual(values = c("blue", "red"), name="Data type", labels=c("Gene segments", "Model"), guide=FALSE) +
geom_area(data=Pvalue, aes(x=value, y=pvalue, fill=variable), position="identity", alpha=0.5) +
scale_fill_manual(values = c("gray"), name="Pvalue", labels=c(""), guide=FALSE)
## Add data type legend: version 1 (data type legend should be on top)
## plotNew <- arrangeGrob(dataleg, stat, heights = unit.c(dataleg$height, unit(1, "npc") - dataleg$height), ncol = 1)
## Add data type legend: version 2 (data type legend should be somewhere in the interior)
## plotNew <- stat + annotation_custom(grob = dataleg, xmin = 7, xmax = 10, ymin = 0, ymax = 4)
grid.newpage()
grid.draw(plotNew)
dev.off()
}
simplot()
내가 (질문 때문에 독립) 질문에 대한 답변에 관심이 있지만를 시각적으로 범례를 사용하는 대신 선을 직접 레이블링 할 수 있습니까? –
@TylerRinker : 당신이 염두에 두어야 할 것이 확실하지 않습니다. 당신은 정교 할 수 있습니까? –
다이렉트 라벨 패키지가이 작업을 수행하는 유일한 방법은 아니지만 [this] (https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQ4Qoq19dCE6mjhpmT5BngK6csAWQL__ZwQPredqteXt3uO0j2j)와 같은 것입니다. 이렇게하면 눈의 검색 량이 줄어들어 처리 요구가 줄어들어 라인의 색상이 의미하는 것이 아닌 작업 메모리의 공간을 차지합니다. –