heatmap with values and some additional features i

2020-03-08 08:09发布

问题:

I am trying to make a heatmap in R, that along with the fill should also show the values and along with filling, should also include a row and column without applying fill on them.

My data looks like this

Year    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Sum
1999    116 127 202 229 253 271 271 245 212 174 133 115 2348
2000    114 154 193 214 263 271 254 248 210 167 120 102 2310
2001    124 134 194 202 256 270 270 243 212 176 128 108 2317
2002    107 137 199 213 267 269 267 250 211 153 123 109 2304
2003    116 141 192 220 229 265 273 242 215 171 122 107 2294
2004    116 146 191 220 245 268 269 253 212 158 115 107 2301
2005    117 132 191 205 263 261 269 244 211 176 132 110 2310
2006    117 125 203 215 246 263 269 248 207 171 128 116 2309
2007    127 133 186 205 244 268 272 251 210 170 133 118 2317
2008    113 146 201 224 259 266 271 245 201 165 128 114 2335
2009    128 145 201 211 243 264 271 247 211 165 126 111 2324
2010    125 128 188 220 254 263 255 234 199 170 127 112 2277
2011    120 131 203 217 241 268 263 247 205 173 131 113 2312
2012    119 133 195 220 241 263 266 249 204 156 120 113 2278
2013    117 142 202 224 248 262 270 249 209 177 117 101 2317
2014    118 144 181 212 233 258 273 250 209 168 126 111 2284
2015    110 132 189 228 257 262 269 241 194 155 113 111 2260
2016    117 147 184 217 253 259 269 238 211 170 123 112 2299
2017    121 147 196 219 260 266 256 242 206 176 132 110 2332
Average 118 138 194 217 250 265 267 246 208 168 125 111 2307

My data doesn't only represent the monthly values but also take in consideration the monthly sum and averages. Making the heat map only with monthly values is not that difficult and I have already done that.

the link to my work is here: code, heatmap

I don't want to include last row and column in the heatmap that represent the sum and average values. I am not sure how can I do that. Please guide me to this. I want to perform this task either with ggplot2 or heatmap package.

I want something like this:

回答1:

We just need to rearrange the data into a long format. Then plot, making sure we only give a subset of the data to geom_tile. Then we rearrange the axis ordering.

library(ggplot2)

dat2 <- stack(dat[-1])
dat2$year <- dat$Year

ggplot(mapping = aes(ind, year)) +
  geom_tile(aes(fill = values), subset(dat2, year != "Average" & ind != "Sum")) +
  geom_text(aes(label = round(values, 1)), dat2) +
  scale_y_discrete(limits = c("Average", 2017:1999)) +
  scale_x_discrete(limits = c(month.abb, "Sum"), position = "top") +
  viridis::scale_fill_viridis() +
  theme_minimal() + theme(axis.title = element_blank())