Home > Blockchain >  Continuous changing linewidth becomes transparent in ggplot
Continuous changing linewidth becomes transparent in ggplot

Time:01-31

I am experimenting with the linewidth aesthetic in ggplot and mainly how to use it for continuously changing a line. When I am trying to create a continuously growing linewidth line, it becomes transparent. Here is some reproducible code:

library(ggplot2)
x = seq(0,2*pi,length.out=10000)
y = sin(x)
df<-data.frame(x=x,y=y, width = seq(from = 0.0001, to = 1,  by = 0.0001))
ggplot(df, aes(x = x, y = y, linewidth = width))  
  geom_line(show.legend = FALSE)

As you can see the gridlines are visible while using 10000 values. When we lower the samples to 100 we can see that the gridlines should not be visible like here:

library(ggplot2)
x = seq(0,2*pi,length.out=100)
y = sin(x)
df<-data.frame(x=x,y=y, width = seq(from = 0.01, to = 1,  by = 0.01))
ggplot(df, aes(x = x, y = y, linewidth = width))  
  geom_line(show.legend = FALSE)

Created on 2023-01-27 with reprex v2.0.2

So I was wondering if anyone knows why the line becomes transparent at 10000 values, which is not what I would expect?

CodePudding user response:

As @teunbrand said completely right in the comments, the line is not perfectly continuously covered because of the small line cutes (a lot of timestamp values). To fix this we could use lineend = "round" to make the ends round of each line like this:

library(ggplot2)
x = seq(0,2*pi,length.out=10000)
y = sin(x)
df<-data.frame(x=x,y=y, width = seq(from = 0.0001, to = 1,  by = 0.0001))
ggplot(df, aes(x = x, y = y, linewidth = width))  
  geom_line(show.legend = FALSE, lineend = "round")

Created on 2023-01-28 with reprex v2.0.2

As we can see, the transparent line is gone.

  • Related