ggplot2 사용 범례에서 점과 선을 어떻게 표현할 수 있습니까?
-
20-09-2019 - |
문제
GGPLOT2를 사용하여 여러 기능과 일련의 포인트를 플로팅하고 있습니다. 전설의 요점을 표현하는 방법을 알 수 없습니다. AES () 함수를 사용해야한다는 것을 알고 있지만이 작업을 수행하는 방법을 완전히 이해하지 못합니다. 예제가 너무 길다는 사실에 사과 드리지만, 어떻게 설명 해야할지 모르겠습니다.
## add ggplot2
library(ggplot2)
# Declare Chart values
y_label = expression("y_axis"~~bgroup("(",val / km^{2},")"))
x_label = "x_axis"
#############################
## Define functions
# Create a list to hold the functions
funcs <- list()
funcs[]
# loop through to define functions
for(k in 1:21){
# Make function name
funcName <- paste('func', k, sep = '' )
# make function
func = paste('function(x){exp(', k, ') * exp(x*0.01)}', sep = '')
funcs[[funcName]] = eval(parse(text=func))
}
# Specify values
yval = c(1:20)
xval = c(1:20)
# make a dataframe
d = data.frame(xval,yval)
# Specify Range
x_range <- range(1,51)
# make plot
p <-qplot(data = d,
x=xval,y=yval,
xlab = x_label,
ylab = y_label,
xlim = x_range
)+ geom_point(colour="green")
for(j in 1:length(funcs)){
p <- p + stat_function(aes(y=0),fun = funcs[[j]], colour="blue", alpha=I(1/5))
}
# make one function red
p <- p + stat_function(fun = funcs[[i]], aes(color="red"), size = 1) +
scale_colour_identity("", breaks=c("red", "green","blue"),
labels=c("Fitted Values", "Measured values","All values"))
# position legend and make remove frame
p <- p + opts(legend.position = c(0.85,0.7), legend.background = theme_rect(col = 0))
print(p)
미리 감사드립니다. 저는 지난 며칠 동안이 커뮤니티로부터 많은 것을 배웠습니다.
해결책
해결책은 아래를 참조하십시오. 주요 아이디어는 다음과 같습니다. 포인트가 보이지 않는 선이 있고 노선이 보이지 않는 점을 가진 선을 상상해보십시오. 따라서 각 "시리즈"는 색상과 모양과 LineType 속성을 가져오고 마지막에 필요에 따라 수동으로 보이지 않는 값 (0, 점의 경우 NA)으로 수동으로 설정합니다. GGPLOT2는 세 가지 속성에 대한 범례를 자동으로 병합합니다.
# make plot
p <- qplot(data = d, x=xval, y=yval, colour="Measured", shape="Measured",
linetype="Measured", xlab = x_label, ylab = y_label, xlim = x_range,
geom="point")
#add lines for functions
for(j in 1:length(funcs)){
p <- p + stat_function(aes(colour="All", shape="All", linetype="All"),
fun = funcs[[j]], alpha=I(1/5), geom="line")
}
# make one function special
p <- p + stat_function(fun = funcs[[1]], aes(colour="Fitted", shape="Fitted",
linetype="Fitted"), size = 1, geom="line")
# modify look
p <- p + scale_colour_manual("", values=c("green", "blue", "red")) +
scale_shape_manual("", values=c(19,NA,NA)) +
scale_linetype_manual("", values=c(0,1,1))
print(p)
다른 팁
각 geom의 색상 미학을 상수로 설정하면 도움이 될 수 있습니다. 다음은 작은 예입니다.
require(ggplot2)
set.seed(666)
N<-20
foo<-data.frame(x=1:N,y=runif(N),z=runif(N))
p<-ggplot(foo)
p<-p+geom_line(aes(x,y,colour="Theory"))
p<-p+geom_point(aes(x,z,colour="Practice"))
#Optional, if you want your own colours
p<-p+scale_colour_manual("Source",c('blue','red'))
print(p)
이것은 GGPLOT2에서 기본적으로 지원되지는 않지만 미래 버전의 방법을 알아낼 수 있기를 바랍니다.
제휴하지 않습니다 StackOverflow