将gg图颜色分配给使用fill = factor()自动指定的颜色不同

时间:2016-10-06 11:46:38

标签: r ggplot2

我正在使用ggplot并使用命令fill = factor(Zone)创建了一个geom_bar图,以便在x轴上显示每个试验(试验1,2)的3个柱(区域a,b,c)。
但是,这也会根据' Zone'自动为我的酒吧分配颜色。 (即区域a =红色,b =蓝色,c =绿色)而不是我的手动调色板。 如何通过试验和区域(即完全不同)保持x轴分离,但是手动或根据另一个参数指定条形颜色?

数据:

  dput(summarydata)
  structure(list(trial = c(1, 1, 1, 2, 2, 2), zone = c("c", "b", 
  "a", "c", "b", "a"), N = c(77, 77, 77, 9, 9, 9), mean = c(24.339207007839, 
  24.3293834745274, 51.3314095176336, 4.97411297139253, 61.7131442273329, 
  33.3127428012746), median = c(24.2125207231389, 24.9084249084249, 
  50.7692307692308, 5.20833333333333, 67.6056338028169, 30.2083333333333
  ), sd = c(9.57972648488188, 10.5885530988102, 17.117966513353, 
  2.96053414557149, 12.2967321565455, 12.5049588941075), se = c(1.0917111525428, 
  1.20667761501389, 1.95077333167849, 0.986844715190498, 4.09891071884851, 
  4.16831963136916)), .Names = c("trial", "zone", "N", "mean", 
  "median", "sd", "se"), row.names = c(NA, -6L), class = "data.frame")

代码:

  Palette1<-c("red", "red", "blue", "red", "green", "blue")

  ggplot(summarydata, aes(x=trial, y=mean, fill=zone))+
  geom_bar(position="dodge",stat="identity") + 
  scale_x_discrete (labels=c ("Trial 1", "Trial 2"))+
  scale_fill_manual (values=Palette1)

2 个答案:

答案 0 :(得分:0)

使用zone变量,每个区域可以有一种颜色。如果您需要每zonetrial一种颜色,则必须创建一个组合trialzone的新变量。例如,这是如何做到的。

library(ggplot2)
# Change trial to a factor (maybe it's already a factor in the original data
# and it was lost in the dput pasted above)
summarydata$trial <- factor(summarydata$trial)
# Create a new variable combining trial and zone
summarydata$trialzone <- paste0("Trial",summarydata$trial,
                                summarydata$zone)
Palette1<-c("red", "red", "blue", "red", "green", "blue")
ggplot(summarydata, aes(x=trial, y=mean, fill=trialzone))+
    geom_bar(position="dodge",stat="identity") + 
    scale_x_discrete(labels = c("Trial 1", "Trial 2")) +
    scale_fill_manual(values = Palette1)

plot using summarydata and factor trial

在评论后编辑

添加其他变量以使图例颜色对应 红色高,蓝色中等,绿色低

summarydata$variable <- factor(c("medium", "high", "high",
                                 "medium", "low", "high"),
                               levels = c("high", "medium", "low"),
                               ordered = TRUE)
Palette2 <- c("red","blue","green")

使用group分隔一次试用中具有相同填充/颜色的zones

ggplot(summarydata, aes(x=trial, y=mean, 
                        fill=variable, group = zone))+
    geom_bar(position="dodge",stat="identity") + 
    scale_x_discrete(labels = c("Trial 1", "Trial 2")) +
    scale_fill_manual(values = Palette2)

highmediumlow

答案 1 :(得分:0)

如果我使用<input name="password" type="password" placeholder="password" id="pass1" /> <input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" /> <div id="error-nwl"></div>,那么我会得到您想要的输出:

fill=Palette1

output