我有一个如下数据框:
df = data.frame(cat = rep(c("A", "B", "C", "D"), each = 20), val = runif(80))
以及如下所示的注释数据框:
ann = data.frame(cat = c("A", "B", "C", "D"), col = c(34, 84, 23, 85))
我想为每个cat
沿x轴绘制一个箱线图,并将数据框中的值作为y轴,但是我还想通过ann$col
(连续颜色映射)。
我可以得到如下的箱线图:
ggplot(df, aes(x = variable, y = BACC)) +
geom_boxplot(width = 0.12)
但是我不确定如何通过类别值给每个箱形图着色。
这怎么办?
谢谢, 杰克
答案 0 :(得分:2)
数据中几乎没有(次要)语法错误。不过,您可能正在寻找:
df <- data.frame(cat = rep(c("A", "B", "C", "D"), 20), val = runif(80))
ann <- data.frame(cat = ("A", "B", "C", "D"),
col = c(34, 84, 23, 85), 20)
library(dplyr) # inner_join comes with dplyr
df_ann <- inner_join(df, ann, by = 'cat') #join both into a three column dataframe
#(cat, val, col) by mathcing column 'cat'.
ggplot(df_ann, aes(x = cat, y = val, fill = col)) +
geom_boxplot(width = 0.12) + scale_fill_gradientn(colours = rainbow(9))