[英]R ggplot2 legend with linetypes
我對 R 比較陌生,我在使用 ggplot2 時遇到了一些困難。 我有一個由三個變量( alpha
、 beta
、 gamma
)組成的數據框,我想將它們繪制在一起。 我得到了情節,但我有兩個問題:
任何想法/建議都非常受歡迎!
p <- ggplot() +
geom_line(data=my.data,aes(x = time, y = alpha,linetype = 'dashed')) +
geom_line(data=my.data,aes(x = time, y = beta, linetype = 'dotdash')) +
geom_line(data=my.data,aes(x = time, y = gamma,linetype = 'twodash')) +
scale_linetype_discrete(name = "", labels = c("alpha", "beta", "gamma"))+
theme_bw()+
xlab('time (years)')+
ylab('Mean optimal paths')
print(p)
如果您首先將數據重新排列為長格式,每行一個觀察,那么您所追求的將更容易實現。
您可以使用 tidyr 的gather
功能來做到這一點。 然后,您可以簡單地將線型映射到數據中的variable
。
在您的原始方法中,您嘗試使用aes()
分配文字“線型”,但 ggplot 將其解釋為您所說的“在此處分配線型,就好像映射到線型的變量具有值 dashed/dotdash/雙破折號'。 繪制繪圖時,它會在默認 scale_linetype_discrete 中查找線型,其前三個值恰好是實線、點線和虛線,這就是您看到令人困惑的替換的原因。 您可以使用scale_linetype_manual
指定線型。
圖例的位置可在theme()
。 legend.position = c(0,1)
定義了放置在左上角的圖例。 legend.justification = c(0,1)
將在圖例框左上角的legend.position
使用的錨點設置。
library(tidyr)
library(ggplot2)
# Create some example data
my.data <- data.frame(
time=1:100,
alpha = rnorm(100),
beta = rnorm(100),
gamma = rnorm(100)
)
my.data <- my.data %>%
gather(key="variable", value="value", alpha, beta, gamma)
p <- ggplot(data=my.data, aes(x=time, y=value, linetype=variable)) +
geom_line() +
scale_linetype_manual(
values=c("solid", "dotdash", "twodash"),
name = "",
labels = c("alpha", "beta", "gamma")) +
xlab('time (years)')+
ylab('Mean optimal paths') +
theme_bw() +
theme(legend.position=c(0.1, 0.9), legend.justification=c(0,1))
print(p)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.