I am trying to use ggplot to plot a grouped barplot. I noticed that the date variable is considered as factor and while plotting R changes its order randomly.
I tried converting the date using as.date(X,format="%m/%d/%Y") but with no help.
Here is my code,
A<-data.frame(A)
A$Date<-as.Date(A$Date, format = "%m/%d/%Y")
Name=XYZ
B<-A[c(1,2,5,6)]
C<-melt(B,id.vars='Date')
C$Date<-as.Date(C$Date, format = "%m/%d/%Y")
ggplot(C,aes(x=Date,y=value))+
geom_bar(aes(fill = variable), position = "dodge", stat="identity")+
scale_fill_brewer(palette="Set1")+
labs(x='Date',y='%Return')+ggtitle('Model')+
theme(plot.title = element_text(hjust = 0.5))+
theme(axis.text.x = element_text(angle = 90, hjust = 1, size=7,color="Black"))+
theme(legend.position = 'bottom')+
theme(legend.text=element_text(size=8))+coord_cartesian( ylim=c(-6, 6))
Before converting Date to the proper date format I got the below output but without the order of Date.
!
After Date conversion, the output changes drastically:
!
Not sure what I am missing out on.
Thanks in advance!
Related
I have been trying to convert POSIXct format so that my date and times would reflect Julian dates.
ind$DateAndTime <- as.POSIXct(ind$DateAndTime, tz = "UTC",
origin = '1970-01-01')
ind$DateAndTime<- format(as.POSIXct(ind_steps$t2),"%y%j")
I had used these two lines of code to do so, but I am now having trouble plotting them using ggplot.
plot_list[[i]] <- ggplot(ind, aes(x = DateAndTime, y = NSD)) +
geom_line() + theme_bw() +
ggtitle(random_tables[i]) +
theme(axis.text.x = element_text(angle = 90))
When I plot it I get this, where the julian dates are vertical, but they still overlap. I would like to get the graph to show the julian dates more visibly and to show every other julian date so that it isn't so cramped in the x-axis. Is there a way to do this?
Here is the completed code. Without any sample data, it is difficult to provide an exact example.
From your previous question, your issue maybe related to attempting to pass a datetime object to a function expecting a date object. In this case I used as.Date() and scale_x_date(), in your case you may want to use as.POSIXct() and scale_x_datetime()
#create dummy data
DateAndTime = 18000:18300
NSD = DateAndTime/10000
ind <-data.frame(DateAndTime, NSD)
#convert the DateAndTime column into a date object
ind$DateAndTime <- as.Date(ind$DateAndTime, tz = "UTC",
origin = '1970-01-01')
#Plot table and format x-axis
ggplot(ind, aes(x = DateAndTime, y = NSD)) +
geom_line() + theme_bw() +
ggtitle("Demo Title") +
scale_x_date(date_breaks = "1 month", date_labels = "%y-%j")
theme(axis.text.x = element_text(angle = 90))
I am new to ggplot library. And trying to draw the plot using the following data.frame:
library(tidyverse)
df <-tribble(~event, ~startdate,~enddate,~loc,
"A",as.POSIXct("1984/02/10"),as.POSIXct("1987/06/10"),"1",
"B",as.POSIXct("1984/02/11"),as.POSIXct("1990/02/12"),"2",
"A",as.POSIXct("1992/05/15"),as.POSIXct("1999/06/15"),"3",
"C",as.POSIXct("2003/08/29"),as.POSIXct("2015/08/29"),"4",
"B",as.POSIXct("2002/04/11"),as.POSIXct("2012/04/12"),"5",
"E",as.POSIXct("2000/02/10"),as.POSIXct("2005/02/15"),"6")
max_date = max(df$startdate,df$enddate)
Using the following code snippet:
ggplot(NULL)+
geom_segment(data = df,aes(x=loc, xend =loc,y = startdate, yend = enddate,colour=event),size = 5,alpha=0.6) +
geom_label(aes(label=df$event,x = df$loc,y=max_date), size=2) +
#geom_point(data=final_df,aes(x=newspaper,y=date),color="black") + Point from other data frame
coord_flip() + xlab("LoC") + ylab("Year")
I can able to output the following chart:
How can I order the above chart using the colour i.e. using the event field (in other word how can I perform group by operation on the event field so that first it should display first all events A then events B, C etc.)? I have tried to use scale_x_continuous and reorder from tidyverse package but it didn't work. How can I display more "Year" on the x-axis? I tried to use scale_x_date (mentioned here R: ggplot display all dates on x axis but it needs as.Date and ggplot geom_segment needs as.POSIXct format). Please feel free to correct me!
Any help would be great! Thank you!
Two options. I've also reversed your x and y so you don't have to use coord_flip() and made several other small modifications including the x-axis labels (you were looking for scale_y_datetime since you flipped the axes and the "dates" were actually in POSIXct). Also, one difference with Duck's answer is my scales = "free" in facet_grid. You might decide your labels and your "loc" variable may not make sense given these new graphs anyway.
library(tibble); library(ggplot2)
df <-tribble(~event, ~startdate,~enddate,~loc,
"A",as.POSIXct("1984/02/10"),as.POSIXct("1987/06/10"),"1",
"B",as.POSIXct("1984/02/11"),as.POSIXct("1990/02/12"),"2",
"A",as.POSIXct("1992/05/15"),as.POSIXct("1999/06/15"),"3",
"C",as.POSIXct("2003/08/29"),as.POSIXct("2015/08/29"),"4",
"B",as.POSIXct("2002/04/11"),as.POSIXct("2012/04/12"),"5",
"E",as.POSIXct("2000/02/10"),as.POSIXct("2005/02/15"),"6")
max_date = max(df$startdate,df$enddate)
ggplot(df)+
geom_segment(aes(y=event, yend = event, x = startdate, xend = enddate, colour=event),size = 5,alpha=0.6) +
geom_label(aes(label=event, y = event, x=max_date), size=2) +
xlab("Year") + ylab("LoC") +
scale_x_datetime(date_breaks = "year", date_labels = "%Y") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
ggplot(df)+
geom_segment(aes(y=loc, yend = loc, x = startdate, xend = enddate, colour=event),size = 5,alpha=0.6) +
geom_label(aes(label=event, y = loc, x=max_date), size=2) +
xlab("Year") + ylab("LoC") +
scale_x_datetime(date_breaks = "year", date_labels = "%Y") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
facet_grid(rows = vars(event), scales = "free")
Created on 2020-10-18 by the reprex package (v0.3.0)
Consider this as an option, as mentioned by #ArthurYip setting reorder could affect the sense of your plot. You could avoid the labels and using facet_grid() in next way:
library(ggplot2)
#Plot
ggplot(df)+
geom_segment(aes(x=loc, xend =loc,y = startdate, yend = enddate,colour=event),size = 5,alpha=0.6) +
coord_flip() + xlab("LoC") + ylab("Year")+
facet_grid(event~.,switch = "x")
Output:
I have a dataframe with one row, i'd like to show it when the horizontal axis is of type datetime. for some reason when I have a single dot, there are no ticks on the horizontal axis.
table_hr_tags_per_bin <- data.frame(matrix(c("2018-11-21 12:40:35", "25"),nrow = 1,ncol = 2))
colnames(table_hr_tags_per_bin) <-c('StartTimeStamp', 'cars')
plot_conf = ggplot() +
geom_point(data = table_hr_tags_per_bin, aes_string(x='StartTimeStamp', y= "cars"),colour = "red", size=3) +
labs(subtitle="plot_name",
y="y_axis_name",
x="Time",
title="my mitle",
caption = "") +
theme(axis.text.x = element_text(angle = 80, hjust = 1)) +
scale_x_datetime(date_breaks = paste0(4," sec"), label=function(x) substr(x,12,19))+
scale_y_continuous(breaks=waiver())
plot(plot_conf)
The problematic output is shown below:
Any suggestion would be helpful!
Maybe I am wrong in anticipating what you mean, if not, I think your datetime and scale_x_datetime use is not right.
If you use lubridate package and the right format for dates, it probably is much easier to get what you want. I have added a second date with a second value for coming nearer to what you wanted with just showing one single point.
library(lubridate)
df <- tibble(dt=c("2018-11-21T12:40:35",
"2018-11-22T12:41:35"),
value=c("25", "26"))
ggplot(df %>% filter(dt < "2018-11-22T12:41:35"), aes(dt, value)) + geom_point()
I have a data frame with a column of dates. I am trying to get a frequency count of each date. I was thinking that a histogram would visualize the data nicely, but maybe there is a better way? I was able to created a histogram of the data but it is not exactly what I was looking for. I was hoping to get each individual date on the x-axis and the frequency count on the y-axis.
I have done some programming in R but I have not done much visualizations in R. Any help would be greatly appreciated.
RawDates<- c("11/8/2017","12/6/2017","10/6/2017","12/6/2017","1/24/2018","9/5/2017","1/24/2018","2/21/2018","10/12/2017","1/22/2018","5/2/2018","1/24/2018","10/12/2017","1/22/2018","2/21/2018","5/2/2018","3/12/2018","5/3/2018","11/7/2017","12/5/2017","9/8/2017","10/6/2017","10/5/2017","11/3/2017","12/6/2017","2/21/2018","11/2/2017","12/5/2017","5/2/2018","1/24/2018","9/6/2017","11/2/2017","2/21/2018","5/2/2018","1/24/2018","11/8/2017","3/12/2018","5/3/2018","1/24/2018")
FormattedDates <- as.Date(RawDates, format = "%m/%d/%Y")
df <- data.frame(FormattedDates)
##This is whatI have already tried
hist(df$FormattedDates, "days", format = "%m/%d/%Y")
Here a simple ggplot2 solution:
library(ggplot2)
library(scales)
ggplot(df) +
geom_histogram(aes(x = FormattedDates)) +
scale_x_date(labels = date_format("%m %d %Y"), date_breaks = "30 days") +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45, hjust = 1))
I am sure this is an easy one but I couldn't find a solution from other posts.
If I run this:
test <- data.frame(dates = as.Date(c("2016-10-31","2016-11-30", "2016-12-31", "2017-01-31")),
values = c(1, 2, 3, 4))
ggplot(test, aes(x = dates, y = values)) +
geom_bar(position="stack", stat = "identity") +
scale_x_date(breaks = date_breaks("1 months"),labels = date_format("%b-%y"))
I get this:
As you can appreciate, all the dates on the X axis are moved forward to the following month.
I tried to use the scales package as suggested elsewhere but it didn't change a thing.
I can get away with this by tweaking the date using:
test$dates <- as.Date(format(test$dates, "%Y-%m-1"))
which delivers this (without using the scale_x_date bit):
but I am sure there is an elegant way to circumvent the problem.
I have run into this problem myself when doing monthly time series charts. My solution: add in a vector of dates into the "breaks = " section.
I.e.
scale_x_date(breaks = test$dates, labels = date_format("%b-%y"))
Note: When I tried "data_breaks" (like your code), I was not able to get it to work under a number of different permutations. The vector of dates only works with "breaks", not "data_breaks"
ggplot(test, aes(x = dates, y = values)) +
geom_bar(position="stack", stat = "identity") +
scale_x_date(breaks = test$dates, labels = date_format("%b-%y"))
P.s. This is my first attempt at answering a question here. I know that the question is old, but hopefully this will help someone!
The labels are correct when you transform dates with as.POSIXct and use scale_x_datetime instead of scale_x_date (no idea why though):
ggplot(test, aes(x = as.POSIXct(dates), y = values)) +
geom_bar(position="stack", stat = "identity") +
scale_x_datetime(breaks = date_breaks("1 months"), labels = date_format("%b-%y"))