3

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.

Fig1A-C Example file (example.txt

Thank you

Heroka
  • 12,889
  • 1
  • 28
  • 38
Vaxin
  • 95
  • 1
  • 10

1 Answers1

2

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 colorbar

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: randcolor

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:

fixed

Jonas Coussement
  • 382
  • 2
  • 15
  • Thank you! That was what I was looking for. – Vaxin Dec 08 '15 at 12:08
  • No problem, you can use the tick mark next to the answer to accept it as solved. Welcome to the site! – Jonas Coussement Dec 08 '15 at 12:14
  • Yes of course! If I may add a question: Now I am trying to have a colorscheme similar to the second image you have posted, I used your code which assigns random colors. However, this means that every new data file looks different, I would like to have a consistent colorscheme. How can I set a specific color scheme that adds as many colors as I have values? – Vaxin Dec 08 '15 at 14:04
  • I have edited my answer to include what you were asking – Jonas Coussement Dec 08 '15 at 14:30