我希望使用ggplot创建单个热图,包括以下因素: 年月,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
热图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")
答案 0 :(得分:1)
我认为您错误地分配了变量。而是尝试:
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")
它回答了您的问题吗?
可复制的示例
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))