1

I have an attendance record with a date column (weekly) and an attendance column for that week.

I just want a bar chart or line graph to show the change over time.

week <- c("09-01-20","09-07-20", "09-21-20")
att <- c(80, 140, 500)
df <- as.data.frame(week,att)

I have tried the following code, but the chart comes up empty or with uniform bars across all dates. A bit confused as I've replicated this from some seemingly straight forward tutorials.

ggplot(df, aes(x=week,y="att")) +
  geom_line()

ggplot(df, aes(x=week,y=att)) +
 geom_line(fill = "identity")

 ggplot(df, aes(x=week,y=att)) +
      geom_bar()
xian_q1
  • 25
  • 8

3 Answers3

1

I think you want a column chart, like this

df <- data.frame(week = c("09-01-20","09-07-20", "09-21-20"),
                 att = c(80, 140, 500))

ggplot(df, aes(x=week, y=att)) +
      geom_col()

Specific to the geom_line, you probably saw the error message:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

To do that, add a group=1 dummy variable, which tells the line, that all the weeks (which are currently strings, consider turning into dates with as.date()) are grouped together. As mentioned here https://stackoverflow.com/a/29019102/10276092

ggplot(df, aes(x=week,y=att, group=1)) +
  geom_line()

enter image description here

M.Viking
  • 5,067
  • 4
  • 17
  • 33
1

I would consider defining the weeks with the as.Date() function, that will help ggplot2 creating the x axis.

week <- as.Date(c("09-01-20","09-07-20", "09-21-20"), format = "%m-%d-%y")
att <- c(80, 140, 500)
df <- data.frame(week,att) # as.data.frame() shouldn't work here

library(ggplot2)

ggplot(df, aes(x=week,y=att)) +
  geom_col() # same as geom_bar(stat = "identity") but less typing

A bar plot

Leonardo Hansa
  • 334
  • 3
  • 8
0

In the OP's geom_bar, specify stat = 'identity'

library(ggplot2)
ggplot(df, aes(x=week,y=att)) +
      geom_bar(stat = 'identity')

-output

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662