[英]Creating lines with different thicknesses in ggplot geom_line
我通過從主數據幀中提取一個小數據幀來繪制與單個用戶(表示為 s)相關的答案的時間序列,然后我使用 ggplot 使用以下代碼進行繪制:
df_s <- df %>%
filter(UserId == s) %>%
select(all_of(c("Answer_Date", questions))) %>%
melt(id.vars = "Answer_Date", variable.name = "Series")
plt <- df_s %>%
ggplot(aes(Answer_Date, value)) +
geom_line(aes(color = Series, linetype = Series)) +
labs(title = paste0(prefix, s),
x = "Answer_Date", y = "Response")
show(plt)
我總共繪制了 6 條線,每條線都有不同的顏色和不同的線型,ggplot 很好地支持了這一點。
如果可能的話,我也想改變線條的粗細,第一條線很粗,后面的線更細。 如果線條的粗細從第一行到最后一行穩步下降,我會很高興。 我試過
geom_line(aes(color = Series, linetype = Series, size = Series))
它有效,但線條太粗了,此外,我收到以下神秘警告:
Warning message:
Using size for a discrete variable is not advised.
我接下來嘗試了這種變體,例如
geom_line(aes(color = Series, linetype = Series, size = (Series/3)))
並且幾乎沒有得到圖表(只有兩三個點)以及更全面的警告:
Warning messages:
1: In Ops.factor(Series, 3) : ‘/’ not meaningful for factors
2: Using size for a discrete variable is not advised.
3: In Ops.factor(Series, 3) : ‘/’ not meaningful for factors
4: Removed 636 row(s) containing missing values (geom_path).
我的第三次嘗試是
geom_line(aes(color = Series, linetype = Series, size = (1, 0.5. 0.5, 0.5, 0.5, 0.5, 0.5)))
這導致了不同的錯誤消息:
Error: unexpected ',' in:
" ggplot(aes(Answer_Date, value)) +
geom_line(aes(color = Series, linetype = Series, size = (1,"
如果有人能指出我的問題的解決方案,我將不勝感激。
提前謝謝了
托馬斯·菲利普斯
也許嘗試使用scale_size_manual()
像這樣:
library(ggplot2)
#Data
df <- data.frame(g=rep(c('G1','G2','G3'),each=10),
index=rep(1:10,3),
val=c(cumsum(rnorm(10,0,1)),cumsum(rnorm(10,5,1)),cumsum(rnorm(10,5,5))))
#Plot
ggplot(df,aes(x=index,y=val,group=g))+
geom_line(aes(color=g,size=g))+
scale_size_manual(values=c(0.1,0.75,1.5))
輸出:
您可以在scale_size
內設置range
,通過將因子水平轉換為數字來否定警告。 這是一個完整的reprex:
library(ggplot2)
set.seed(2)
df <- data.frame(Series = rep(LETTERS[1:6], each = 100),
value = as.numeric(replicate(6, cumsum(rnorm(100)))),
Date = seq(as.Date("2020-01-01"), length = 100, by = "day"))
ggplot(df, aes(Date, value, color = Series)) +
geom_line(aes(size = -as.numeric(Series))) +
scale_size(range = c(0.5, 2), guide = guide_none()) +
scale_color_brewer(palette = "RdPu", name = "Series") +
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.