I want to plot a time series for data in seconds. I tried to use ggplot with this:
p <- ggplot(df_new, aes(x=Time, y=Price))
geom_line(aes(color = Price), size = 1)
The output is like this:
However, the line is not clear, can anyone help me.
CodePudding user response:
You can separate date
from time
and try creating a heatmap with geom_tile()
.
library(ggthemes)
library(ggplot2)
library(tidyverse)
ggplot(df, aes(x = Time, y = Price, group=1))
geom_line(linetype = "dashed" , color="red", lwd=1)
geom_point(color="blue",size=3)
labs(x="Date and Time", y="Price")
coord_flip()
theme_clean()
theme(axis.text.x = element_text(angle= 45, hjust = 1, face="bold", size=12, color="black"),
axis.title.x = element_text(face="bold", size=16, color="black"),
axis.text.y = element_text(face="bold", size=12, color="black"),
axis.title.y = element_text(face="bold", size=16, color="black"))
scale_x_discrete(labels=df$Time)
Plot:
You can separate Date
and Time
with this code:
df <- separate(df, col = Time, into = c('Date', 'Time'), sep = ' ')
Plot:
I would suggest using geom_tile()
Sample code:
library(ggplot2)
library(ggthemes)
library(tidyverse)
df <- separate(df, col = Time, into = c('Date', 'Time'), sep = ' ')
ggplot(df, aes(x = Time, y = Date))
geom_tile(aes(fill = Price))
labs(x="Time", y="Date")
theme_pander()
theme(axis.text.x = element_text(angle=45,hjust = 1, face="bold", size=12, color="black"),
axis.title.x = element_text(face="bold", size=16, color="black"),
axis.text.y = element_text(face="bold", size=12, color="black"),
axis.title.y = element_text(face="bold", size=16, color="black"),
legend.text = element_text(color = "black", size = 16,face="bold"),
legend.title = element_text(face="bold", size=16, color="black"),
legend.position="right",
legend.background = element_rect(color = NA, size=4),
legend.key.size = unit(1, 'cm'))
Plot:
Sample data:
df<-structure(list(Time = c("2018-02-21 09:00:00", "2018-02-21 09:07:38",
"2018-02-21 09:09:10", "2018-02-21 09:09:10", "2018-02-21 09:09:21",
"2018-02-21 09:13:16"), Price = c(122.1, 122.4, 122.4, 122.4,
122.2, 122.3)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
CodePudding user response:
Something like this?
library(lubridate)
library(tidyverse)
df %>%
distinct() %>%
mutate(Time = period_to_seconds(hms(format(strptime(Time, "%Y-%m-%d %H:%M:%OS"), "%H:%M:%S"))),
Time = cumsum(Time - lag(Time, default = first(Time)))) %>%
ggplot(aes(x = Time, y = Price))
geom_line()
theme_bw()
Output
Or if you are wanting to show the full date, then you could do something like this:
df %>%
mutate(Time = as.POSIXct(Time, format = "%Y-%m-%d %H:%M:%OS")) %>%
ggplot(aes(x = Time, y = Price))
geom_line()
theme_bw()
scale_x_datetime(breaks = "60 sec", date_labels = "%H:%M:%S")