การซ้อนทับแปลงใน ggplot2

จะวางซ้อนพล็อตหนึ่งไว้ด้านบนของอีกอันใน ggplot2 ตามที่อธิบายไว้ในประโยคต่อไปนี้ได้อย่างไร ฉันต้องการวาดอนุกรมเวลาสีเทาที่ด้านบนของอนุกรมเวลาสีแดงโดยใช้ ggplot2 ใน R (ตอนนี้อนุกรมเวลาสีแดงอยู่เหนืออนุกรมเวลาสีเทา และฉันต้องการให้กราฟของฉันเป็นอย่างอื่น) นี่คือรหัสของฉัน (ฉันสร้างข้อมูลบางส่วนเพื่อแสดงปัญหาของฉัน ชุดข้อมูลจริงซับซ้อนกว่ามาก):

install.packages("ggplot2")
library(ggplot2)

time <- rep(1:100,2)
timeseries <- c(rep(0.5,100),rep(c(0,1),50))
upper <- c(rep(0.7,100),rep(0,100))
lower <- c(rep(0.3,100),rep(0,100))
legend <- c(rep("red should be under",100),rep("grey should be above",100))

dataset <- data.frame(timeseries,upper,lower,time,legend)

ggplot(dataset, aes(x=time, y=timeseries)) +
  geom_line(aes(colour=legend, size=legend)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_colour_manual(limits=c("grey should be above","red should be under"),values = c("grey50","red")) +
  scale_fill_manual(values = c(NA, "red")) +
  scale_size_manual(values=c(0.5, 1.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())

person user3577165    schedule 26.04.2014    source แหล่งที่มา
comment
คุณสามารถให้ข้อมูลตัวอย่างสำหรับ data frame ได้หรือไม่?   -  person sriramn    schedule 27.04.2014
comment
ใช้พารามิเตอร์ alpha ในเส้น geom ของคุณ   -  person rawr    schedule 27.04.2014
comment
ฉันไม่ต้องการเปลี่ยนระดับความโปร่งใสของอนุกรมเวลาหนึ่ง แต่ฉันต้องการให้อนุกรมหนึ่งอยู่เหนืออีกอนุกรมหนึ่ง ตอนนี้คุณสามารถเรียกใช้ codenow ได้แล้ว ฉันได้เพิ่มข้อมูลบางส่วนในโพสต์ต้นฉบับแล้ว   -  person user3577165    schedule 27.04.2014
comment
เพียงแค่สลับคำสั่งซื้อ ใส่คำสั่ง geom_line ของคุณที่ส่วนท้ายเพื่อให้เลเยอร์เส้นสีเทาเป็นเลเยอร์สุดท้ายและอยู่ด้านบนสุด   -  person Ramnath    schedule 27.04.2014
comment
ฉันลองสิ่งนี้แล้ว แต่มันใช้งานไม่ได้ อาจเป็นเพราะฉันต้องการเพิ่มคำอธิบายแผนภูมิด้วยคำสั่ง aes(color=legend, size=legend) ด้วย   -  person user3577165    schedule 27.04.2014


คำตอบ (1)


แปลงข้อมูลที่คุณกำลังจัดกลุ่มเป็นปัจจัยและกำหนดลำดับของระดับอย่างชัดเจน ggplot วาดเลเยอร์ตามลำดับนี้ นอกจากนี้ เป็นความคิดที่ดีที่จะจัดกลุ่มโค้ด scale_manual เข้ากับ geom ที่ใช้เพื่อให้อ่านง่าย

legend <- factor(legend, levels = c("red should be under","grey should be above"))

c <- data.frame(timeseries,upper,lower,time,legend)

ggplot(c, aes(x=time, y=timeseries)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_fill_manual(values = c("red", NA)) +
  geom_line(aes(colour=legend, size=legend)) +
  scale_colour_manual(values = c("red","grey50")) +
  scale_size_manual(values=c(1.5,0.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())

โปรดทราบว่าการเรียงลำดับของค่าใน scale_manual ตอนนี้จับคู่กับ "สีเทา" และ "สีแดง"

ป้อนคำอธิบายรูปภาพที่นี่

person sriramn    schedule 27.04.2014