对于我想要的多个(此处:两个)值列表
我已经使用ggplot2提出了两个例子的组合,ggplot2仍然使用不同颜色的线条图和直方图。它也可能有点多余,创建
如何为折线图和直方图获得相同的颜色?
额外奖励:如何缩短使用过的源代码?
我的结果:
源代码(R):
# input data lists
vals_x <- c(4, 3, 6, 7, 4, 6, 9, 3, 0, 8, 3, 7, 7, 5, 9, 0)
vals_y <- c(6, 6, 4, 8, 0, 3, 7, 3, 1, 8, 2, 1, 2, 3, 6, 5)
# ------------------------------------------------
library(ggplot2)
library(gridExtra)
# prepare data for plotting
df <- rbind( data.frame( fill = "blue", obs = vals_x),
data.frame( fill = "red", obs = vals_y))
test_data <- data.frame(
var0 = vals_x,
var1 = vals_y,
idx = seq(length(vals_x)))
stacked <- with(test_data,
data.frame(value = c(var0, var1),
variable = factor(rep(c("Values x","Values y"),
each = NROW(test_data))),
idx = rep(idx, 2),
fill_col = c( rep("blue", length(vals_x)),
rep("red", length(vals_y)))))
# plot line
p_line <- ggplot(stacked, aes(idx, value, colour = variable)) +
geom_line()
# plot histogram
p_hist <- ggplot( df, aes(x=obs, fill = fill)) +
geom_histogram(binwidth=2, colour="black", position="dodge") +
scale_fill_identity()
# arrange diagrams
grid.arrange( p_line, p_hist, ncol = 2)
答案 0 :(得分:1)
最简单的事情是
ggplot
对象scale_*_manual
(或其他scale
电话)。 所以
## Particularly awful colours
p_hist = ggplot(stacked, aes(x=value, fill=variable)) +
geom_histogram(binwidth=2, colour="black", position="dodge") +
scale_fill_manual(values=c("red", "yellow"))
p_line = ggplot(stacked, aes(idx, value, colour = variable)) +
geom_line() +
scale_colour_manual(values=c("red", "yellow"))
顺便说一句,我不会在这里使用直方图;箱线图或密度图会好得多。