簡體   English   中英

當一個情節使用ggplot覆蓋另一個時,如何制作自定義圖例?

[英]How to make a custom legend when a plot overlays another using ggplot?

我需要制作一個堆積直方圖,繪制兩個不同的變量。 有一個名為T1的變量,另一個名為T2變量。 這兩個變量有兩種不同的狀態,一種發生在之前,另一種發生在之后。 我想有一個圖,我將在一列中顯示T1T2 ,它們的狀態在前后,但使用兩種不同的顏色(一種指示之前的狀態,另一種指示之后的狀態)。

這是我到目前為止的代碼片段:

pre <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(60,"T1",40,"T2") ) )
post <- as.data.frame( matrix( nrow=2,ncol=2,byrow=TRUE,c(70,"T1",50,"T2") ) )
pre$V1 <- as.numeric(as.character(pre$V1))
post$V1 <- as.numeric(as.character(post$V1))

ggplot() +
geom_histogram(stat="identity", fill=c(rep("red",2)), data=post, aes(x=V2, y=V1, fill=V2, colour="Before")) +
geom_histogram(stat="identity", fill=c(rep("green",2)), data=pre, aes(x=V2, y=V1, fill=V2, colour="After")) +
scale_x_discrete("x axis") +
scale_y_continuous("y axis", limits = c(0, 100)) +
scale_colour_manual(values = c("red","green"))

因此情節看起來很神奇,但是現在我的問題是,我怎樣才能得到一個合適的傳奇? 所以我需要為"After"設置一種顏色,為"Before"另一種顏色,但不是作為線條,而是填充框。

首先,在制作條形圖時,請使用geom_bar() 然后對於fill=color=內部aes()使用相同的名稱,然后調整顏色並填充scale_..函數。

ggplot() +
  geom_bar(stat="identity",  data=post, aes(x=V2, y=V1, fill="Before",color="Before")) +
  geom_bar(stat="identity", data=pre, aes(x=V2, y=V1, fill="After",color="After")) +
  scale_x_discrete("x axis") +
  scale_y_continuous("y axis", limits = c(0, 100)) +
  scale_fill_manual("Legend",values = c("green","red"))+
  scale_color_manual("Legend", values = c("red","green"))

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM