按颜色名称列填充直方图

时间:2015-06-29 16:01:02

标签: r ggplot2

我有一个组合数据集的功能,并为每个颜色分配颜色,如下面的代码所示

x1 <- rep(1:10, each = 3, times = 3)
x2 <- rep(1:7, each = 7, times = 2)
x3 <- rep(6:9, each = 11, times = 4)
y1 <- rep(1:5, each = 2, times = 9)
y2 <- rep(1:14, times = 7)
y3 <- rep(1:11, times = 16)
color1 <- rep("blue", times = length(x1))
color2 <- rep("red", times = length(x2))
color3 <- rep ("green", times = length(x3))
data1 <- cbind(x1, y1, color1)
data2 <- cbind(x2, y2, color2)
data3 <- cbind(x3, y3, color3)
alldata <- data.frame(rbind(data1, data2, data3))
colnames(alldata) <- c("x", "y", "color")

ggplot(data = alldata, aes(x=x), position = "dodge")
+ geom_histogram(fill =      alldata$color)

ggplot(data = alldata, aes(x=x, y=y)) + geom_point(colour = alldata$color)

我想知道为什么没有将颜色分配给直方图,但它们被提供给散点图的点。

我得到的错误是

Error: Incompatible lengths for set aesthetics: fill

基本上,数据按颜色分组,我希望分配给每个组的颜色是直方图中表示的颜色。

1 个答案:

答案 0 :(得分:1)

您希望将颜色变量映射为填充并使用这些值而不进行缩放:

ggplot(alldata, aes(x=x, fill = color)) +
  geom_histogram(position = "dodge") +
  scale_fill_identity()
相关问题