Time series in R with ggplot2

I am new to ggplot2 and ask a fairly simple question about time series plots.

I have a data set in which data is structured as follows.

      Area 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
  MIDWEST   10    6   13   14   12    8   10   10    6    9

How to create a time series when data is structured in this format.

With the package, reshapeI could just change the data to look like this:

totmidc <- melt(totmidb, id="Area")
totmidc

    Area    variable  value
1  MIDWEST     1998    10
2  MIDWEST     1999     6
3  MIDWEST     2000    13
4  MIDWEST     2001    14
5  MIDWEST     2002    12
6  MIDWEST     2003     8
7  MIDWEST     2004    10
8  MIDWEST     2005    10
9  MIDWEST     2006     6
10 MIDWEST     2007     9

Then run the following code to get the desired schedule.

ggplot(totmidc, aes(Variable, Value)) + geom_line() + xlab("") + ylab("")

However, is it possible to plot a time series with the first object in which the columns represent years.

+3
source share
2 answers

What is the error ggplot2 gives? The following works on my machine:

Area <-  as.numeric(unlist(strsplit("1998 1999 2000 2001 2002 2003 2004 2005 2006 2007", "\\s+")))
MIDWEST <-as.numeric(unlist(strsplit("10    6   13   14   12    8   10   10    6    9", "\\s+")))

qplot(Area, MIDWEST, geom = "line") + xlab("") + ylab("")

#Or in a dataframe

df <- data.frame(Area, MIDWEST)
qplot(Area, MIDWEST, data = df, geom = "line") + xlab("") + ylab("")

ggplot2 scale_date .

+4

, " " , ?

, geom_bar(). geom_bar - stat_bin, x. stat_identity.

library(ggplot2)

# Recreate data
totmidc <- data.frame(
        Area = rep("MIDWEST", 10),
        variable = 1998:2007,
        value = round(runif(10)*10+1)
)

# Line plot
ggplot(totmidc, aes(variable, value)) + geom_line() + xlab("") + ylab("")

# Bar plot
# Note that the parameter stat="identity" passed to geom_bar()
ggplot(totmidc, aes(x=variable, y=value)) + geom_bar(stat="identity") + xlab("") + ylab("")

:

enter image description here

+3

Source: https://habr.com/ru/post/1791563/


All Articles