簡體   English   中英

使用ggplot2添加圖例

[英]adding a legend using ggplot2

我想在圖表中添加圖例。

但這對我來說很難。

所以請幫我

library(ggplot2)
library(scales)
library(grid)
library(gcookbook)
data<-read.csv("maxmin.csv")
attach(data)
head(data)
str(data)

to<-ggplot(data,aes(x=obs,y=toaverage)) + geom_ribbon(aes(ymin=tomin,ymax=tomax),alpah=0.9,fill="grey50")  + geom_line(colour="black")+ labs(x = "", y = "")+ scale_y_continuous(breaks=seq(0,70,10))+ expand_limits(max(data$tomax),y=c(0,70))
to<-to + theme(axis.text.x=element_blank())+ geom_ribbon(aes(ymin=tomax25,ymax=tomax75),alpah=0.9,fill="grey30") + theme(axis.ticks.x=element_blank())
to<- to +  theme(line = element_blank())+ theme(text = element_text(size=15)) 
to<-to + geom_line(aes(y=toaverage),colour="black")

這是工作。

我想在底部添加圖例

to<-to+ scale_colour_manual(value=c("black","grey50",grey"30"), breaks=c("toaverage","tomax","tomax25"), labels=c("average","(max,min)","(25%,75%)"))+ theme(legend.position="bottom")

但這是行不通的。

(tomax25和tomax75是最大和最小的分位數)

實際上,我想添加一條平均線,並且grey50和grey 30是顏色框。

我該如何解決這個問題。

在此先感謝您。

因此,這應該可以幫助您入門。

# create sample dataset - you should provide this!!!
x <- 1:10
set.seed(1)   # for reproducibble example
df <- data.frame(x,y=rnorm(100,mean=sample(x,10)))
gg <- aggregate(y~x,df,fivenum)
gg <- with(gg,data.frame(x,gg[,2]))
colnames(gg) <- c("x","tomin","tomax25","toaverage","tomax75","tomax")

# you start here, more or less...
library(ggplot2)
ggplot(gg,aes(x=x))+
  geom_ribbon(aes(ymin=tomin,ymax=tomax,fill="Full.Range"),alpha=0.9)+
  geom_ribbon(aes(ymin=tomax25,ymax=tomax75,fill="IQR"),alpha=0.9)+
  geom_line(aes(y=toaverage,color="Mean"))+
  scale_color_manual(name="",values=c(Mean="orange"),guide=guide_legend(order=1))+
  scale_fill_manual(name="",values=c(Full.Range="grey70",IQR="grey30"),
                    breaks=c("Mean","IQR","Full.Range"))

我的評論以及引用的帖子中的要點是,要獲得傳奇,您必須創建一個美觀的貼圖。 通過在aes(...)的調用內放置對顏色/填充的引用來實現此目的。 然后,您可以使用scale_fill_manual(...)通過將values=...設置為顏色的命名向量來設置填充顏色,如上所示。

暫無
暫無

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

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