Alternate title: replacing a continuous legend with a discrete legend in ggplot2
I'm trying to create a stacked bar chart using this code:
DataTest = data.frame(Order = 1:7,
Data = c(340, 464, 93, 218, 16, 206, 103),
Category = factor(c("Free", "Unavailable", "Free",
"Unavailable", "Free", "Unavailable", "Free"),
levels = c("Free", "Unavailable")))
ggplot(DataTest, aes(x="Thing", y=Data, fill=Category)) +
geom_bar(position="stack", stat="identity")
Ignore x, it's unimportant. The plotted graph looks like this:
Stacked bar chart with 2 blocks of solid colour
The problem is, I want the data to be ordered like the rows in my data frame, so the stacked bar chart should be striped with alternating colours, like this:
In fact, this bar chart is exactly what I want - aside from the legend. I want the legend to show just two colours, but I can't figure out how to set that up.
The code for this bar chart is:
DataTest[["Category"]] = c(1, 0, 1, 0, 1, 0, 1) # change Category from a factor to numeric
ggplot(DataTest, aes(x="Thing", y=Data, fill=Category)) +
geom_bar(position="stack", stat="identity")
The same as the previous snippet, but this time Catgeory is a numeric vector of only 1s and 0s. If I use a logical vector instead of numeric, once again the bars are grouped by colour.
Here's one last thing I tried:
ggplot(DataTest, aes(x="Thing", y=Data, fill=Order, colour=Category)) +
geom_bar(position="stack", stat="identity")
Messy bar chart that has some order but is nevertheless grouped by Category
Which shows that despite stat="identity", ggplot is insisting on sorting the data.
SO.
To be clear, I can't figure out how to sort my data by Order, but colour my data according to Category - except by introducing a continuous legend, which I don't want.