Ggplot histogram for time series

I read Hadley Wickham's book on ggplot, but I have problems determining weight over time on a bar graph. Here is an example of data:

dates <- c("20040101","20050101","20060101") dates.f <- strptime(dates,format="%Y%m%d") m <- rbind(c(0.2,0.5,0.15,0.1,0.05),c(0.5,0.1,0.1,0.2,0.1),c(0.2,0.2,0.2,0.2,0.2)) m <- cbind(dates.f,as.data.frame(m)) 

In this data.frame, the first column shows the dates and each row of the corresponding weights. I would like to draw weights for each year on the histogram using the "fill" argument.

I can display weights in columns using:

 p <- ggplot(m,aes(dates.f)) p+geom_bar() 

However, this is not quite what I want. I would like to see in each bar the contribution of each weight. Moreover, I don’t understand why I have a strange x-axis format, that is, why β€œ2004-07” and β€œ2005-07” are displayed.

thanks for the help

+6
source share
2 answers

Hope this is what you are looking for:

ggplot2 requires data in a long format.

 require(reshape2) m_molten <- melt(m, "dates.f") 

The construction itself is performed

 ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) + geom_bar(stat="identity") 

enter image description here

You can add position="dodge" to geom_bar , if you wish, next to each other.

EDIT

If you want only one-time breaks: convert m_molten$dates.f to a date.

 require(scales) m_molten$dates.f <- as.Date(m_molten$dates.f) ggplot(m_molten, aes(x=dates.f, y=value, fill=variable)) + geom_bar(stat="identity") + scale_x_date(labels = date_format("%y"), breaks = date_breaks("year")) 

PS: See http://vita.had.co.nz/papers/tidy-data.pdf for Hadley's neat data philosophy.

+3
source

To create the plot that you need, you must change your data from β€œwide” to β€œhigh”. There are many ways to do this, including the reshape() function in the R database (not recommended), reshape2 and tidyr .

In the tidyr package, you have two functions for modifying data, gather() and spread() .

The gather() function converts from wide to high. In this case, you need to collect your columns V1:V5 .

Try the following:

 library("tidyr") tidy_m <- gather(m, var, value, V1:V5) ggplot(tidy_m,aes(x = dates.f, y=value, fill=var)) + geom_bar(stat="identity") 

enter image description here

+1
source

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


All Articles