【问题标题】:Cut values to intervals and plot a heatmap in ggplot2将值切割为间隔并在 ggplot2 中绘制热图
【发布时间】:2020-07-14 03:33:29
【问题描述】:

给定一个数据框如下:

df <- structure(list(year = c(2001L, 2001L, 2001L, 2001L, 2002L, 2002L, 
2002L, 2002L, 2003L, 2003L, 2003L, 2003L), quater = c(1L, 2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), value = c(4L, 23L, 14L, 
12L, 6L, 22L, 45L, 12L, 34L, 15L, 3L, 40L)), class = "data.frame", row.names = c(NA, 
-12L))

输出:

    year  quater  value
0   2001       1      4
1   2001       2     23
2   2001       3     14
3   2001       4     12
4   2002       1      6
5   2002       2     22
6   2002       3     45
7   2002       4     12
8   2003       1     34
9   2003       2     15
10  2003       3      3
11  2003       4     40

如何绘制类似于下图的图表:

请注意此数据集中的yearquater 对应于上图中的yearweek

我需要先cutvalue 列由(0, 10], (10, 20], (20, 30], (30, 40], (40, 50] 然后绘制它们。

我试过的代码:

ggplot(df, aes(week, year, fill= value)) + 
  geom_tile() +
  scale_fill_gradient(low="white", high="red")

输出:

如您所见,图例与我需要的不同。

感谢您的帮助。

【问题讨论】:

  • ggplot 之前添加df %&gt;% mutate(value = cut(value, seq(0, 50, 10))) ?
  • 你能在答案中发布完整的代码吗?
  • 我建议 df %&gt;% mutate(value = cut(value, seq(0, 50, 10))) %&gt;% ggplot() + aes(quater, year, fill = value) + geom_tile()scale_fill_gradient 但不适用于因子。
  • 是的,传说似乎没有改变。

标签: r ggplot2 dplyr


【解决方案1】:

您应该首先使用cut 获取类(正如Ronak Shah 已经提到的),然后您可以使用scale_fill_brewer 更改图块的颜色。

library(tidyverse)

df %>%
  mutate(class = cut(value, seq(0, 50, 10))) %>%
  ggplot(aes(quater, year, fill = class) ) + 
  geom_tile() + 
  scale_fill_brewer(type = "seq",
                    direction = 1,
                    palette = "RdPu")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多