【问题标题】:ggplot color based on total number of factors, not just factors in plot in Rggplot颜色基于因子总数,而不仅仅是R中的绘图因子
【发布时间】:2015-09-30 20:13:07
【问题描述】:

我正在尝试制作两个情节。一个显示了变量 x 按因子 category1 拆分的箱线图,第二个图是相同的,但针对变量 y。

我在下面提供了可重现的代码。

require(ggplot2)

dataset <- data.frame(category1 = rep(LETTERS[1:5], 100),
                  y = rnorm(500, mean = rep(1:5, 100)),
                  z = rnorm(500, mean = rep(c(1:4,NA), 100)))

ggplot(dataset, aes(x=factor(category1), y=y, fill=category1)) + geom_boxplot()
ggplot(dataset, aes(x=factor(category1), y=z, fill=category1)) + geom_boxplot()

这些图都很好,只是我希望颜色能够通过,即 category1 中 A 的颜色始终是相同的红色阴影。我知道 ggplot 是基于色轮除以 5,然后分别除以 4 进行着色的,但我不知道如何使它始终除以 5 并始终使用相同的颜色,即使没有值 E在因子 z 中,在第二个图中。

【问题讨论】:

  • 您可以手动设置颜色:+ scale_fill_manual(values = palette("default")) 到每个绘图
  • @scoa,这行得通。我结合了一种方法来模拟here中的ggplot颜色选择方法,以产生所需的效果。该解决方案似乎并不像 ggplot 那样优雅。
  • scale_fill_discrete(drop = FALSE)this answer 一样吗?在the answers here 中针对更复杂的情况提供了一些更复杂的答案。
  • @aosmith 是的!这似乎可以做到,我没有看到那个答案,但是另一个使用 scale_fill_discretevalues 我包含的参数似乎使它不起作用。我将在下面更新我的答案以反映您的评论。

标签: r plot ggplot2


【解决方案1】:

您应该手动设置颜色以确保在两个绘图中使用相同的调色板。这是一个使用默认调色板的示例:

+ scale_fill_manual(values = palette("default"))

RColorBrewer 有优雅的预定义调色板,您可以在their website 上浏览。

library(RColorBrewer)
ggplot(...) + 
  scale_fill_brewer(palette = "Accent")

【讨论】:

  • 我也喜欢 RColorBrewer 颜色选项。为此,我认为scale_fill_brewer() 也可以用来代替scale_fill_manual()
【解决方案2】:

达到预期效果的最简单和最优雅的方法是使用scale_fill_discrete,请参见下面的示例第二个绘图代码:

ggplot(dataset, aes(x=factor(category1), y=z, fill=category1)) +
    geom_boxplot() + scale_fill_discrete(drop=FALSE)

但是,也可以使用以下附加代码来完成,该代码创建一个用于绘图的调色板,然后手动设置颜色以使用此调色板。该解决方案的好处是允许用户定义任何调色板以用作固定方案。解决方案来自代码here 和上面@scoa 的答案。

require(ggplot2)

dataset <- data.frame(category1 = rep(LETTERS[1:5], 100),
                  y = rnorm(500, mean = rep(1:5, 100)),
                  z = rnorm(500, mean = rep(c(1:4,NA), 100)))

n <- length(levels(dataset$category1)) 
hues = seq(15, 375, length=n+1)
cpt <- hcl(h=hues, l=65, c=100)[1:n]

ggplot(dataset, aes(x=factor(category1), y=y, fill=category1)) + 
    geom_boxplot() + scale_fill_manual(values = cpt)
ggplot(dataset, aes(x=factor(category1), y=z, fill=category1)) + 
    geom_boxplot() + scale_fill_manual(values = cpt)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-26
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2020-09-06
    • 2021-10-15
    • 2019-03-04
    相关资源
    最近更新 更多