简体   繁体   中英

How to plot a line chart in ggplot with a date and time axis?

I have a simple dataset that contains three columns of hourly observations over the course of a few days.

The data looks something like...

Time                    Fast    Standard   Slow
Aug 02 2020 18:00:00    100     200        300
Aug 02 2020 19:00:00    50      100        150
Aug 02 2020 18:00:00    100     200        300
Aug 03 2020 12:00:00    50      100        150
Aug 03 2020 11:00:00    40      50         70

数据

I start by loading up the CSV:

library(tidyverse)

# Link source
if (!exists("gasprices")) { # Check if the object is not already loaded
  if (file.exists("./datafiles/gasprices.rdata")) {
    load("./datafiles/gasprices.rdata") 
  } else {
    gasprices <- read.csv("./datafiles/gasprices.csv")
  }

But when I go to plot one of the lines, I get a blank plot. I think R is showing every row, when what I really need is three overall change-over-time lines for the three variables (fast, standard, slow). My ideal outcome would show three lines of different colors changing over time in the x axis.

# Plot
g <- ggplot(gasprices, aes(x=Time, y=Fast)) +
  geom_line(color = "#00AFBB", size = 2)
  xlab("") +
  theme_light()
g

在此处输入图像描述

Any help would be greatly appreciated. Thank you,

It's likely to do with the column data-types. Try running the below for your dataframe, what do you get?

lapply(gasprices, class)

Try setting the datatype to a datetime before plotting:

gasprices$Time<- as.POSIXct(gasprices$Time, format = "%b %e %Y %H:%M:%S")

Have a look at this page for details about the providing the format to be used to parse the datetime.

Let me know how it goes!

What you should do is use the tidyverse package to unpivot your data.

  require(ggplot2)
  require(tidyr)
  require(dplyr)  

Lets create a dataframe with the same structure:

Data <- data.frame ( time = c(1,2,3), fast = c(100, 105, 110), slow = c(50, 70, 90), standart = c(94, 95, 96))

  time fast slow standart
1    1  100   50       94
2    2  105   70       95
3    3  110   90       96

Now we unpivot the data.

Data %>%
  tidyr::gather(key = 'Speed Type', value = 'Speed Value', -time)

 time Speed Type Speed Value
    1       fast         100
    2       fast         105
    3       fast         110
    1       slow          50
    2       slow          70
    3       slow          90
    1   standart          94
    2   standart          95
    3   standart          96

ggplot2::ggplot(data = UnpivotData, mapping = ggplot2::aes(x = time, y = `Speed Value`, color = `Speed Type`)) + 
    ggplot2::geom_line()

在此处输入图像描述

You must convert your dates to numeric values before you can plot lines with ggplot() . Perhaps this thread will help you. After doing this, you must provide new axis tick labels to your plot, for example:

plot + scale_x_discrete(labels= df$Time)

Here is a full example with date-to-numeric along with assigning axis tick labels:

library(reshape2)

# Make data frame
Lines <-"Time                    Fast    Standard   Slow
Aug 02 2020 18:00:00    100     200        300
Aug 02 2020 19:00:00    50      100        150
Aug 02 2020 20:00:00    100     200        300
Aug 03 2020 12:00:00    50      100        150
Aug 03 2020 11:00:00    40      50         70"

df <- read.csv(text = gsub("  +", ",", readLines(textConnection(Lines))),
                check.names = FALSE)

# Convert date string to proper format
df$Time <- as.POSIXct(df$Time, format = "%b %d %Y %H:%M:%S")

# Reshape data for easier plotting. This function is from Reshape2.
df <- melt(df, id = "Time")

# Plot
ggplot(data = df, aes(x = as.numeric(Time), y = value, color = variable)) +
  geom_line() +
  scale_x_continuous(breaks = as.numeric(df$Time), labels = as.character(df$Time)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 1, hjust=1))

exampleplot

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM