想让我的ggplot有不同的颜色?

时间:2018-04-22 21:31:12

标签: r ggplot2 colors

caries <- structure(list(subject = 1:69, inst = c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), 
    before = c(7L, 20L, 21L, 1L, 3L, 20L, 9L, 2L, 11L, 15L, 7L, 
    17L, 9L, 1L, 3L, 10L, 13L, 3L, 4L, 4L, 15L, 6L, 4L, 18L, 
    11L, 9L, 4L, 5L, 11L, 4L, 4L, 7L, 0L, 3L, 0L, 8L, 2L, 13L, 
    9L, 15L, 13L, 2L, 9L, 4L, 10L, 7L, 14L, 7L, 3L, 9L, 8L, 19L, 
    10L, 10L, 7L, 13L, 5L, 1L, 8L, 4L, 4L, 14L, 8L, 3L, 11L, 
    16L, 8L, 0L, 3L), after = c(11L, 24L, 25L, 2L, 7L, 23L, 13L, 
    4L, 13L, 18L, 10L, 17L, 11L, 5L, 7L, 14L, 17L, 4L, 7L, 9L, 
    18L, 8L, 6L, 19L, 12L, 9L, 7L, 7L, 14L, 6L, 4L, 7L, 4L, 3L, 
    1L, 8L, 4L, 18L, 12L, 18L, 17L, 5L, 12L, 6L, 14L, 11L, 15L, 
    10L, 6L, 12L, 10L, 19L, 13L, 12L, 11L, 12L, 8L, 3L, 9L, 5L, 
    7L, 14L, 10L, 5L, 12L, 18L, 8L, 1L, 4L), treat = structure(c(3L, 
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 3L, 
    3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 
    1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("APF", "SF", 
    "W"), class = "factor")), .Names = c("subject", "inst", "before", 
"after", "treat"), class = "data.frame", row.names = c(NA, -69L
))

这是我的代码到目前为止 - 龋齿是导入的数据集。

我试图让三个不同的盒子变成不同的颜色,现在它们只是在道奇蓝色。

数据

public class Test4 {
public static void main(String[] args) {
     int a[] = {1, 2, 2, 3, 3, 3, 6,6,6,6,6,66,7,65}; 
              int newlength =    lengthofarraywithoutduplicates(a);
              for(int i = 0 ; i < newlength ;i++) {
                  System.out.println(a[i]);
              }//for
}//main

private static int lengthofarraywithoutduplicates(int[] a) {
     int count = 1 ;
     for (int i = 1; i < a.length; i++) {
          int ch = a[i];
          if(ch != a[i-1]) {
              a[count++] = ch;
          }//if
    }//for
    return count;

}//fix

}//end1

https://pastebin.com/MeRw69ky&lt;

2 个答案:

答案 0 :(得分:0)

为了让变量确定绘图中的颜色,您必须在aes调用中将该变量映射为颜色。这是mpg数据集的示例。我建议阅读ggplot2 docs,因为那里有很多例子,其中至少有一个与此基本相同。

library(ggplot2)

ggplot(mpg, aes(x = class, y = hwy, color = class)) +
    geom_boxplot()

reprex package(v0.2.0)创建于2018-04-22。

答案 1 :(得分:0)

我已使用此代码修复了它。谢谢大家的帮助!

ggplot(caries, aes(inst, Teeth, group=inst, fill = inst)) + geom_boxplot()

ggplot(caries, aes(treat, Teeth, group=treat, fill = treat)) + geom_boxplot()