ggplot

时间:2015-09-09 18:07:03

标签: r ggplot2

我们说我有以下数据集:

set.seed(1)
df <- data.frame(
  Index = 1:10,
  Heat = rnorm(10),
  Cool = rnorm(10),
  Other = rnorm(10),
  a = rnorm(10),
  b = rnorm(10)
)

现在我想针对Index创建每个列的折线图。我这样做的方式如下:

df.plot <- ggplot(
  data = tidyr::gather(df, key = 'Variable', value = 'Component', -Index),
  aes(x = Index, y = Component, color = Variable)
) +
  geom_line()

但现在我想改变它,以便变量Heat,Cool和Other分别为红色,蓝色和绿色。所以我尝试了类似的东西:

set.colors <- c(Heat = 'red', Cool = 'blue', Other = 'green')
df.plot + scale_color_manual(values = set.colors)

这里的问题是set.colors变量没有足够的颜色(a和b没有表示)但我只是想让ggplot自动为这两个变量分配颜色,因为在我的实际中代码,没有办法告诉这些列有多少。所以我基本上希望ggplot能够进行正常的颜色分配,然后搜索任何名为Heat,Cool或Other的变量(不保证这三个中的任何一个或全部都存在)和然后分别将颜色更改为红色,蓝色和绿色,而不更改任何其他变量的颜色。

2 个答案:

答案 0 :(得分:1)

将您自己的颜色与默认调色板混合是一个令人惊讶的坏主意。不过,这里有一种方法可以做到这一点 - 与其他答案类似,但可能更为通用,并且根据您的要求使用ggplot的默认调色板。

library(ggplot2)
library(reshape2)
gg.df <- melt(df, id="Index", value.name="Component")
ggp <- ggplot(gg.df, aes(x = Index, y = Component, color = variable)) +
  geom_line()

lvls  <- levels(gg.df$variable)
cols  <- setNames(hcl(h=seq(15, 375, length=length(lvls)+1), l=65, c=100),lvls)
cols[c("Heat","Cool","Other")] <- c("#FF0000","#0000FF","#00FF00")

ggp + scale_color_manual(values=cols)

编辑:刚才意识到我从未说过为什么这是一个坏主意。 This post进入它,并有一些非常好的参考。主要的一点是,选择默认颜色是出于一个很好的理由,而不仅仅是为了使情节&#34;看起来很漂亮&#34;。所以除非有极大的需求,否则你真的不应该把它们搞得一团糟。

答案 1 :(得分:0)

以下内容可能有效。首先,我设置了色标:

plot_data <- tidyr::gather(df, key = 'Variable', value = 'Component', -Index)
vars <- levels(plot_data$Variable)
colours <- character(length(vars))
colours[vars=="Heat"] <- "red"
colours[vars=="Cool"] <- "blue"
colours[vars=="Other"] <- "green"
other_colours <- c("orange", "purple", "brown", "gold")
others <- !(vars %in% c("Heat", "Cool", "Other"))
colours[others] <- other_colours[1:sum(others)]

想法是首先手动分配所需的颜色,然后将某些列表中的颜色分配给其他元素。如果other_colours需要更多颜色,则可以使用colours()获取指定颜色的完整列表。

然后情节产生于:

ggplot(plot_data, aes(Index, Component, colour = Variable)) + 
          geom_line() +
          scale_colour_manual(values = colours)

我不认为可以使用scale_colour_manual并让ggplot自动选择一些颜色。

相关问题