Reputation: 1089
I am plotting a time series of answers associated with a single user (denoted s) by extracting a small dataframe from the main dataframe which I then plot using ggplot using the code below:
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)
I plot 6 lines in all, and each line has a different color as well as a different line type, and ggplot supports this beautifully.
I'd like, if possible, to vary the thickness of the lines as well, with the first line being thick, and subsequent lines being thinner. I'd be almost as happy if the thickness of the lines just declined steadily from the first line to the last. I tried
geom_line(aes(color = Series, linetype = Series, size = Series))
and it works, but the lines are much too thick, and, in addition, i get the following cryptic warning:
Warning message:
Using size for a discrete variable is not advised.
I next tried variants of this such as
geom_line(aes(color = Series, linetype = Series, size = (Series/3)))
and barely got a graph (just two or three points) as well as a more comprehensive warning:
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).
My third attempt was
geom_line(aes(color = Series, linetype = Series, size = (1, 0.5. 0.5, 0.5, 0.5, 0.5, 0.5)))
which resulted in a different error message:
Error: unexpected ',' in:
" ggplot(aes(Answer_Date, value)) +
geom_line(aes(color = Series, linetype = Series, size = (1,"
I'd be very appreciative if someone could point me to the solution to my problem.
Many thanks in advance
Thomas Philips
Upvotes: 3
Views: 716
Reputation: 173803
You can set the range
inside scale_size
, negating the warning by converting your factor levels to numeric. Here's a full 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()
Upvotes: 3
Reputation: 39595
Maybe try using scale_size_manual()
like this:
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))
Output:
Upvotes: 6