Search code examples
rhistogramstacked

Creating bar borders for a stacked histogram in R


I have a set of data:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

I want to create a stacked histogram:

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
geom_bar(stat = "identity")

Now I want to include a black border for each bar so that it is clearer visually. I though this would work:

ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
geom_bar(stat = "identity")+geom_histogram(colour = "black")

However, this is not what I want.
Issue 1: there is no black border in each bar.
Issue 2: there is an extra diagonal line for each group in the legend. I want to remove this line.

I wonder if anyone can let me know what I have done wrong and what is the correct way to include a black border for each bar in the histogram.

Many thanks.


Solution

  • upgrade comment.

    To get the border just add the colour="black" to the geom_bar call, in your first plot. A quick fix for the black line in the legend is to plot two geom_bar calls, suppressing the legend in the call with the border. You can then add a black border to the legend with the legend.key theme

    ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
         geom_bar(stat = "identity") + 
         geom_bar(stat = "identity", colour="black", show_guide=FALSE)   +
         theme(legend.key = element_rect(colour = "black", size=1.5))