如何在ggplot中为独立层缩放颜色?

时间:2012-10-03 20:55:01

标签: r scale ggplot2

我有一个记录三栋建筑能耗的数据集。我有一个融化的数据框,可以从钻石集中模仿:

data <- melt(diamonds[,c('depth','table','cut','color')],id=c('cut','color'))

基本上,我有来自三个不同建筑物(7'颜色'因子)的每个月('切割')的加热('深度')和冷却('表')数据。我想在每个月的条形图中并排绘制三个建筑物(7'颜色'因子)('cut')。

我希望代表冷却('表')或加热('深度')的条形根据建筑物('颜色'因子)改变其阴影,同时保持按月分组('切割')。这是一种可视化钻石数据的坏方法,但应该适用于建筑物,因为它们的加热和冷却月份通常不会重叠。到目前为止,我有:

p <- ggplot(data,
        aes(color,value,group=cut))
p <- p + geom_bar(stat = 'identity',
              position = 'dodge',
              aes(fill = variable))
print(p)

我尝试使用scale_fill_manual,但无法想出有效的策略:

colours <- c('#0000FF', '#0033FF', '#0066FF', '#FF0000', '#FF3300', '#FF6600')

p <- p + scale_fill_manual(values = colours,
                           group = data$variable)

1 个答案:

答案 0 :(得分:6)

有些诡计,有可能。派生基于钻石的数据集是非常好的,但我想使用较小的数据集

set.seed(1234)
data <-
expand.grid(month = month.abb,
            building = c("Building A", "Building B", "Building C"),
            hc = c("Heating", "Cooling"))
data$value <- rnorm(nrow(data), 60, 10)

您希望填充颜色基于变量(hc)和建筑物(building),因此请将其设置为该互动。

ggplot(data, aes(building,value,group=month)) + 
  geom_bar(stat = 'identity',
           position = 'dodge',
           aes(fill = interaction(building, hc)))

enter image description here

我们可以选择代表不同近色调的颜色,使它们更像您想要的颜色。我使用了RColorBrewer调色板的“蓝调”和“红色”的中间部分。

colours <- c("#FC9272", "#FB6A4A", "#EF3B2C", "#9ECAE1", "#6BAED6", "#4292C6")
# library("RColorBrewer")
# colours <- c(brewer.pal(9,"Reds")[4:6], brewer.pal(9,"Blues")[4:6])

并使用scale_fill_manual分配这些颜色。

ggplot(data, aes(building,value,group=month)) + 
  geom_bar(stat = 'identity',
           position = 'dodge',
           aes(fill = interaction(building, hc))) +
  scale_fill_manual(values=colours)

enter image description here

真正的诡计在于让传奇变得更加错综复杂。我只列出了2个级别(中间建筑的颜色)并给它们不同的名称(以及不同的标题标题)。

ggplot(data, aes(building,value,group=month)) + 
  geom_bar(stat = 'identity',
           position = 'dodge',
           aes(fill = interaction(building, hc))) +
  scale_fill_manual("Heating/cooling",
                    values=colours,
                    breaks=c("Building B.Heating", "Building B.Cooling"),
                    labels=c("Heating", "Cooling"))

enter image description here