簡體   English   中英

圖例和多個 geom_line

[英]Legend and multiple geom_line

我有多行到 plot 並且我希望將數據分為 3 類。 請在此處找到可復制的示例:

x <- c(1:20, 1:20,1:20,1:20,1:20,1:20,1:20)
variable <- c(rep("y1", 20), rep("y2", 20),rep("y3", 20),rep("y4", 20),rep("y5", 20),rep("y6", 20),rep("y7", 20))
value <- c(rnorm(20), rnorm(20,1),rnorm(20,2),rnorm(20,3),rnorm(20,5),rnorm(20,6),rnorm(20,7))
type=c(rep("A",100),rep("B",40))

df <- data.frame(x, variable, value,type)
library(ggplot2)
d <- ggplot(df, aes(x=x, y=value, group=variable, colour=type)) + geom_line(size=0.5,alpha=0.6)+
geom_line(data=subset(df,variable=="y6"),size=2,alpha=1,col="blue")+            
geom_line(data=subset(df,variable=="y7"),size=2,alpha=1,col="black")

我預計圖例 plot 中有 3 個類別:“A”組為細紅線,“y6”組為藍色,“y7”為黑色和粗線。 我怎樣才能正確設置圖例?

非常感謝你的幫助,ochees

錯誤的傳說情節

歡迎來到 SO! 處理您的數據而不是處理ggplot (記得放一個set.seed(123)以使您的數據也可用於其他人):

# define the colors
df$color <- ifelse(df$variable == 'y6', 'A',ifelse(df$variable == 'y7', 'B','C'))
# define the size of the lines
df$size <- ifelse(df$variable %in% c('y6','y7'),2,0.5)

# here a custom palette of colors
myColors <-c("black","blue","red")
names(myColors) <- levels(df$color)
colScale <- scale_colour_manual(name = "grp",values = myColors)

# here the plot, adding your color palette, and the columns created
library(ggplot2)
ggplot(df, aes(x=x, y=value, group=variable,color=color)) +
 geom_line(size= df$size,alpha=1) +
 colScale

在此處輸入圖像描述

謝謝s_t的回答。 但是,我不能將此方法應用於我的數據集。

請找到我的數據集

set.seed(123)
ZS=c(rep(0,4),rep(300,4),rep(600,4),rep(900,4),rep(1200,4),rep(1500,4),rep(1800,4),rep(2100,4),rep(2400,4),rep(2700,4),rep(3000,4))
MEAN=c(21+rnorm(4),19+rnorm(4),17+rnorm(4),15+rnorm(4),13+rnorm(4),12+rnorm(4),13+rnorm(4),9+rnorm(4),6+rnorm(4),5+rnorm(4),1+rnorm(4))
Model_short=c(rep(c("mod3","mod4","obs1","obs2"),11))
color=c(rep(c("r","r","ref1","ref2"),11))
size=c(rep(c(0.5,0.5,1,1),11))
alpha=c(rep(c(0.5,0.5,1,1),11))

data=data.frame(
ZS=ZS,
MEAN=MEAN,
Model_short=Model_short,
color=color,
size=size,
alpha=alpha)

和這里的腳本:

library(ggplot2)
myColors=c("#4CA54C","#000000","#717171")
names(myColors) <- levels(data$color)
colScale <- scale_colour_manual(name = "grp",values = myColors)

p<-ggplot(data,aes(x = ZS,y=MEAN,group=Model_short,color=color)) + 
geom_line(size=data$size,alpha=data$alpha)+
theme_bw()+theme(legend.position = "right")+
ylab("ylab")+
xlab("xlab")+ 
coord_flip()+ggtitle("title")+colScale
print(p)

非常感謝

plot_x_y

暫無
暫無

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

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