0

I am trying to plot a time vs temperature graph in ggplot. My data frame looks something like this:

              Time Temperature
1 07-10-2021 22:00       99.59
2 08-10-2021 02:00      101.50
3 08-10-2021 06:00      101.30
4 08-10-2021 10:00      100.40
5 08-10-2021 14:00       99.80
6 08-10-2021 18:00      100.69
7 08-10-2021 19:00       98.90
8 08-10-2021 20:00       97.50

Running the following code, I am getting the desired results, but the x-axis tick mark labels look very cluttered. I just want to show the time in 24 hr format and not the respective date.

library(ggplot2)
library(ggthemes)

data <- read.csv(file.choose())

plot <- ggplot(data, aes(Time, Temperature, group = 1)) +
  geom_point() + 
  geom_line(size = 1.5, color = "magenta") +
  labs(x = "\nTime",
       y = "Temperature in fahrenheit\n")+
  scale_y_continuous(breaks = c(96,97,98,99,100,101,102,103),limits = c(96, 104))+
  geom_text(aes(label = Temperature), color = "white", vjust = -1.5)

plot + theme(
  plot.margin = margin(2,2,2,2, unit = "cm"),
  panel.background = element_rect(fill = "black", color = "gray20"),
  plot.background = element_rect(fill = "black"),
  panel.grid.major = element_line(color = "gray30"),
  panel.grid = element_line(color = "gray30"),
  axis.title = element_text(color = "white", size = rel(1.5)),
  axis.text = element_text(face = "bold", color = "white")
)

I want the code to be fully reproducible so that one could enter the time in 24 hr format and the respective temperature in CSV file, import, run and get access to their plots, so I don't want to explicitly use a string as labels.

tahoor21
  • 1
  • 1
  • Just be aware that if you do as you say you want to do, Monday 11h and Tuesday 11h would plot to the same position! – dario Oct 08 '21 at 13:46
  • @dario But I am not using weekdays in my data. R would differentiate among dates, right? – tahoor21 Oct 08 '21 at 15:15
  • Not if you just keep the time in 24h format and remove any date information. – dario Oct 08 '21 at 15:20
  • Ohh yes, in fact, that's why I added the date. Earlier I was using only time in 24h format and ran into the same problem you mentioned. – tahoor21 Oct 08 '21 at 15:23
  • Changing the format of the x-axis is addressing the *symptom*, but it is ignoring the fact that you are plotting a **continuous**-like variable (a timestamp) as **categorical** on your plot. The correct way to fix the *problem* is to convert your `"Time"` column to `POSIXt`-class, and use `ggplot2::scale_x_datetime` if you want the format to be just time-of-day. – r2evans Oct 08 '21 at 15:46
  • I'd start with `data$Time <- as.POSIXct(data$TimeTime, format = "%d-%m-%Y %H:%M"))`, then later use `... + scale_x_datetime(date_labels = "%H:%M")`. – r2evans Oct 08 '21 at 15:49
  • (That should be `data$Time`, not `TimeTime`, of course ...) – r2evans Oct 08 '21 at 15:58

0 Answers0