this is my first post and I am new to coding, I apologise if my post is not clean or I havent looked for answers enough.
I am trying to plot a stacked bar graph with ggplot2 and am almost there. Here is what I have so far. I have a data set with 2 columns (Length and Count). I have attached it to this post. I read it and plot it like this:
example <- read.delim("example.txt", sep",")
ggplot(data=example, aes(x=Length, y=Count, fill=Count))+geom_bar(stat="identity")
The graph this gives me is Fig1A
What I am looking for, however, is that every value in the column "Count" is given its own color. It should look like Fig1B (Excel example):
I tried to plot it the way I would plot it in Excel (Fig1C) but was not able to replicate this kind of plot with ggplot2, I wasnt able to have my data.frame fit this kind of layout.
Example file (example.txt
Thank you
Try using the column count as a factor, rather than the column itsself.
ggplot(data=example, aes(x=Length, y=Count, fill=factor(Count)))+geom_bar(stat="identity")
returns
ggplot automatically chooses a gradient color scale, but you can change it with a different color palette or a manual list of colors for each factor. For example, you can choose a random color for each level in your dataset by calling:
colors <- sample(colours(),length(levels(factor(example$Count))))
and adding this to your plot
+ scale_fill_manual(values = colors)
which gives something similar to this:
alternatively, you can choose to follow R's built in color codes. Try running
colours()
and you will get a full list of available colors. You can hand pick as many as you need or you can select the first n elements, with n equal to your amount of levels
colors <- colours()[seq(1,length(levels(factor(example$Count))),by=1)]
and following the above procedure. That consistently gives this graph: