Creating a Y variable that's a count of the X variable

Viewed 580

This is a simple question and all the answers I've found have been for more complicated datasets.

I'm trying to create a line graph with X as dates and Y as a count of each individual X variable (the autogenerated 'rownames').

Have tried:

ggplot(data=o2outcomes, aes(x=transfusion_date, y=..count.., group=1)) +
  geom_line()

y x   
1 01/01/99 01:01,   
2 01/01/99 02:02,   
3 01/02/99 01:01

The code will be run frequently with new dates added, so I can't just assign the number of y variables as static 1,2,3, it needs to be a count of the x axis.

3 Answers

A plot with the y-variable equal to the count of the number of instances of each x-variable is easy in base R:

plot(table(x))

The table() function creates (as its name suggests) a table containing a vector of the number of occurrences of each value in x, with names corresponding to each x value.

To specify a line graph, we use the plot argument type='l', and we can also (optionally) specify the y-axis limits to ensure that zero is included using ylim=. Also, to make it a little prettier when using a vector of strings representing dates (which are usually too long to fit next-to-each-other if plotted horizontally as x-axis labels), we can use the plot argument las=2 to display the x-axis labels vertically, and we can remove the x-axis title using xlab="".

All together:

my_dates=c("3/28/20 18:01", "3/28/20 22:16", "4/1/20 19:30", "4/1/20 23:56", "4/10/20 17:36", "4/10/20 20:30","3/28/20 18:01", "3/28/20 22:16")

plot(table(my_dates),type="l",ylim=c(0,2),las=2,xlab="",ylab="# of each date/time")

enter image description here

It's not as simple as you may believe in a first place. There is (to my knowledge) no direct way to use a count variable with geom_line. So (as also suggested in this answer), it is better and easiest to first create a summary frame.

Here a pure tidyverse approach.

library(tidyverse)
library(lubridate)

dates <- data.frame(x = c("3/28/20 18:01", "3/28/20 22:16", "4/1/20 19:30", "4/1/20 23:56", "4/10/20 17:36", "4/10/20 20:30"))
dates <- 
  dates %>%
  mutate(x = as_date(mdy_hm(x))) %>%
  count(x) 

ggplot(data = dates, aes(x = x, y = n, group = 1)) +
  geom_line()

Created on 2020-05-16 by the reprex package (v0.3.0)

try below code:

library(lubridate)
library(ggplot2)
library(scales)
a<-c("3/28/20 18:01", "3/28/20 22:16", "4/1/20 19:30", "4/1/20 23:56", "4/10/20 17:36", "4/10/20 20:30","3/28/20 18:01", "3/28/20 22:16")
b<-table(a) %>% as.data.frame()
b$a<-mdy_hm(b$a)
ggplot(b,aes(x = b$a, y = b$Freq, group = 1)) + geom_line()+ scale_x_datetime(labels = date_format("%d%b"))

enter image description here

Related