Getch
Getch

Reputation: 107

Filling histogram by column of color names

I have a function that combines data sets and assigns colors to each like the code seen below

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)

I was wondering why the colors aren't being assigned to the histogram, but they are being supplied to the points of the scatter plot.

The error I'm getting is

Error: Incompatible lengths for set aesthetics: fill

Essentially the data is being grouped by color, and I want the color assigned to each group to be the color represented in the histogram.

Upvotes: 1

Views: 649

Answers (1)

aaronwolen
aaronwolen

Reputation: 3753

You want to map your color variable to fill and use those values without scaling:

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

Upvotes: 1

Related Questions