I have the following data frame
df
Time Load1 Load2
0 375.5 375.5
10 374.6 374.6
20 350.1 350.1
30 334.5 334.5
40 304.9 347.7
50 285.4 331.6
.... .... .. ...
I am unable to change the format of the Time column from 10,20 to be like this: 00:10, 00:20...
I want to draw this data frame using ggplot by this command:
P<- ggplot(df,aes(Time))+
geom_line(aes (y=0))+
geom_vline(xintercept = 0,)+
geom_line(aes(y=Load2,linetype = "twodash"))+
geom_line(aes(y=Load1, linetype = "solid"))+
theme(legend.position='none')+ # to remove the legend.
geom_vline(xintercept = 650, colour="purple",linetype ="longdash")+
geom_vline(xintercept = 1500, colour="purple",linetype ="longdash")+
geom_vline(xintercept = 2200, colour="purple",linetype ="longdash")+
labs(title = "Daily load demands", x = "Time of day", y = "Power
consumption_Kw/h")
P
however, the currently result is :
I tried following command to change the time format :
df<- data.frame(Time,Load1,Load2)
df$Time <- as.POSIXct(df$Time, format="%H:%M:%S")
P<- ggplot(df,aes(df$Time))+...
But there is no change. please, is there any suggestion to draw the x-axis in the format 05:00, 10:00, 15:00, 20:00 instead of 500, 1000,1500,2000. many thanks.
I guess this can be your solution. If is only a problem of visualisation (and not of data) why don't you simply change the Labels in ggplot? You can use something similar to (Note: the code I am giving you here is simply an example that DON'T APPLY to your case)
scale_x_continuous( breaks = c(2012,2013,2014,2015,2016, 2017),
labels = c ("A","B","C","D","E","F"))
That would change labels on the x-axis from years to letters.
I can't tell the format of your Time entry beyond 60 minutes, but here is a possible solution. Other manipulation may be needed depending on the minute format of your data.
Convert the minutes to appropriate format, first left-pad with 0's (uses stringr package):
df$Time <- stringr::str_pad(df$Time, 4, "left", pad = "0" )
or the sprintf()
from the link above is a simple, elegant solution that does the same: df$Time <- sprintf("%04d", df$Time)
One might work better depending on your original Time format.
then convert this to a POSIXct format time:
df$Time <- strptime(df$Time, format = "%H%M")
Then format the time appropriately in ggplot. Using your existing plot, just add:
P + scale_x_datetime(labels = date_format("%H:%M"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.