I am putting a number of limit lines on a time series plot on ggplot and am including the name of each of the limit lines on the chart. I would then like to convert that ggplot to interactive plot using ggplotly.
When I add the text using geom_text I receive the message ‘All aesthetics have length 1, but the data has 3556 rows. ℹ Please consider using annotate()
or provide this layer with data containing a single row.’ I’ve tried annotate but get the error, Error: unexpected ‘,’ in:
” ylim(0, 67)+
annotate(geom=”text”, x=as.Date(“2024-06-30 00:08:51″)),”
Any help greatly appreciated.
# Set seed for reproducibility
set.seed(123)
# Generate 100 sequential datetimes
start_datetime <- Sys.time()
datetimes <- seq(from = as.POSIXct(start_datetime), by = "15 mins", length.out = 3556)
# Generate 3556 random discharge values between 1 and 38
discharge <- runif(3556, min = 1, max = 38)
# Create the data frame
df <- data.frame(datetime = datetimes, discharge = discharge)
# interactive plot using plotly
Plot1<-ggplot(df,aes(datetime, discharge))+geom_point(size=0.5)+
xlab("Date")+ylab("Discharge(cumec)")+
scale_x_datetime(labels = date_format("%d %b %Y"))+
ylim(0, 67)+
geom_hline(yintercept = 66.69, linetype='dashed', color='purple', linewidth=1)+
geom_text(aes(x=min(datetime), y=66, label="MEM", vjust=-0.5), color='purple')+
geom_hline(yintercept = 31.85, linetype='dashed', color='orange', linewidth=1)+
geom_text(aes(x=min(datetime), y=31.85, label="SAM", vjust=-0.5), color='orange')+
geom_hline(yintercept = 15.936, linetype='dashed', color='red', linewidth=1)+
geom_text(aes(x=min(datetime), y=15.936, label="BEM", vjust=-0.5), color='red')+
geom_hline(yintercept = 3.605, linetype='dashed', color='yellow', linewidth=1)+
geom_text(aes(x=min(datetime), y=3.605, label="PIP", vjust=-0.5), color='yellow')+
geom_hline(yintercept = 0.183, linetype='dashed', color='turquoise', linewidth=1)+
geom_text(aes(x=min(datetime), y=0.183, label="NIP", vjust=-0.5), color='turquoise')
Plot1
Plot2<-ggplot(df,aes(datetime, discharge))+geom_point(size=0.5)+
xlab("Date")+ylab("Discharge(cumec)")+
scale_x_datetime(labels = date_format("%d %b %Y"))+
ylim(0, 67)+
annotate(geom="text", x=as.Date("2024-06-30 00:08:51")), y=66.69, label="MEM", color='purple'
Plot2
#> Error: <text>:41:58: unexpected ','
#> 40: ylim(0, 67)+
#> 41: annotate(geom="text", x=as.Date("2024-06-30 00:08:51")),
#> ^
Created on 2024-06-25 with reprex v2.1.0