简体   繁体   中英

Time Series Heat Map

I wish to create a single heatmap using ggplot including following factors: year-month, mkt_name, mp_price

str(df)

   'data.frame':    2655 obs. of  5 variables:
 $ year      : int  2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 ...
 $ yearmonthf: Factor w/ 48 levels "Jan 2012","Feb 2012",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ month     : int  1 2 3 4 5 6 7 8 9 10 ...
 $ mkt_name  : Factor w/ 63 levels "Base","Birambo",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ mp_price  : num  145 136 160 163 181 ...
df <- read.csv('/Users/shashankshekhar/Desktop/R Food Price/Foodprice/datasets/Correlation/Heatmap/Potatoesheat.csv')
df$date <- as.Date(df$date)  # format date
df <- df[df$year >= 2012, ]  # filter reqd years

# Create Month Week
df$yearmonth <- as.yearmon(df$date)
df$yearmonthf <- factor(df$yearmonth)
df <- df[, c("year", "yearmonthf", "month", "mkt_name", "mp_price")]

head(df)

   year yearmonthf month mkt_name mp_price
15 2012   Jan 2012     1  Birambo   145.00
16 2012   Feb 2012     2  Birambo   136.25
17 2012   Mar 2012     3  Birambo   160.00
18 2012   Apr 2012     4  Birambo   162.75
19 2012   May 2012     5  Birambo   181.00
20 2012   Jun 2012     6  Birambo   170.00

Heatmap ggplot

ggplot(df, aes(mkt_name, year, fill = mp_price)) + 
  geom_tile(colour = "white") + 
  facet_grid(year~mkt_name) + 
  scale_fill_gradient(low="red", high="green") +
  labs(x="Week of Month",
       y="",
       title = "Time-Series Calendar Heatmap", 
       subtitle="Potato Price", 
       fill="Price")

I think you mis-attributed your variables. Instead try:

ggplot(df, aes(x = yearmonth, y = mkt_name, fill = mp_price))+
  geom_tile()+
  scale_x_date(date_labels = "%b %Y")+
  scale_fill_gradient(low="red", high="green") +
  labs(x="Week of Month",
       y="",
       title = "Time-Series Calendar Heatmap", 
       subtitle="Potato Price", 
       fill="Price")

在此处输入图片说明

Does it answer your question ?


reproducible example

df <- data.frame(mkt_name = rep("Birambo",6),
                 year = 2012,
                 yearmonth = seq(as.Date("2012-01-01", format = "%Y-%m-%d"), as.Date("2012-06-01", format = "%Y-%m-%d"), by = "month"),
                 month = 1:6,
                 mp_price = c(145,136.25,160,162.75,181,170))

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