Creating a Bar Plot with Proportions on ggplot - r

I'm trying to create a bar graph on ggplot that has proportions rather than counts, and I have c+geom_bar(aes(y=(..count..)/sum(..count..)*100)) but I'm not sure what either of the counts refer to. I tried putting in the data but it didn't seem to work. What should I input here?
This is the data I'm using
> describe(topprob1)
topprob1
n missing unique Info Mean
500 0 9 0.93 3.908
1 2 3 4 5 6 7 8 9
Frequency 128 105 9 15 13 172 39 12 7
% 26 21 2 3 3 34 8 2 1

You haven't provided a reproducible example, so here's an illustration with the built-in mtcars data frame. Compare the following two plots. The first gives counts. The second gives proportions, which are displayed in this case as percentages. ..count.. is an internal variable that ggplot creates to store the count values.
library(ggplot2)
library(scales)
ggplot(mtcars, aes(am)) +
geom_bar()
ggplot(mtcars, aes(am)) +
geom_bar(aes(y=..count../sum(..count..))) +
scale_y_continuous(labels=percent_format())

You can also use ..prop.. computed variable with group aesthetics:
library(ggplot2)
library(scales)
ggplot(mtcars, aes(am)) +
geom_bar(aes(y=..prop.., group = 1)) +
scale_y_continuous(labels=percent_format())

Related

R: barplot inconsistent width

I have two sets of data
Co1 Col2
1 10
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
I put these two data into two variables Num and Leaf respectively
and I tried to plot them with barplot(Leaf,Num, space=0.5,col="red")
Everything is fine, besides that some bars have larger width than the others. While some other bars have no width and literablly became a line.
Why is that?
I know i can fix it by doing barplot(Leaf,Num, space=0.5,col="red", width=0.5)
But I am wondering why the default behavior of such function gives you inconsistent bar width
In base R you can do
barplot(df$Col2, names.arg = df$Co1)
Or using ggplot
library(ggplot2)
ggplot(df, aes(as.factor(Co1), Col2)) + geom_col() + xlab("Co1")
dataset = data.frame(Leaf,Num)
barplot(dataset$Leaf,dataset$Num,space=0.5,col="red")
or
barplot(Leaf,Num,space=0.5,col="red")

ggplot multiple lines in same graph

I am trying to plot multiple gene expressions over time in the same graph to demonstrate a similar profile and then add a line to illustrate the mean of total for each timepoint (like the figure 4b in recent Nature comm article https://www.nature.com/articles/s41467-017-02546-5/figures/4). My data has been normalised to be around 0 so they are all on the same scale.
df2 sample:
variable value gene
1 5 -0.610384193 1
2 5 -6.25967087 2
3 5 -3.773389731 3
50 6 -0.358879035 1
51 6 -6.066341017 2
52 6 -4.202998579 3
99 7 -0.103885903 1
100 7 -6.648844687 2
101 7 -5.041554127 3
I plot the expression levels with ggplot2:
plotC <- ggplot(df2, aes(x=variable, y=value, group=factor(gene), colour=gene)) + geom_line(size=0.5, aes(color=gene), alpha=0.4)
But adding the mean line in red to this plot is proving difficult. I calculated the means and put them in another dataframe:
means
value variable gene
1 -1.5037354 5 50
2 -0.8783492 6 50
3 -0.7769085 7 50
Then tried adding them as another layer:
plotC + geom_line(data=means, aes(x=variable, y=value, color="red", group=factor(gene)), size=0.75)
But I get an error Error: Discrete value supplied to continuous scale
Do you have any suggestions as to how I can plot this mean on the same graph in another color?
Thank you,
Anna
edit: the answer by RG20 is helpful, thanks for pointing out I had the color in the wrong place. However it plots the line outside the rest of the graph... I really don't understand what's wrong with my graph...
enter image description here
plotC + geom_line(data=means, aes(x=variable, y=value, group=factor(gene)), color='red',size=0.75)

using geom_bar to plot the sum of values by criteria in R

I'm new in R and I am trying to use ggplot to create subsets of bar graph per id all together. Each bar must represent the sum of the values in d column by month-year (which is c column). d has NA values and numeric values as well.
My dataframe, df, is something like this, but it has actually around 10000 rows:
#Example of my data
a=c(1,1,1,1,1,1,1,1,3)
b=c("2007-12-03", "2007-12-10", "2007-12-17", "2007-12-24", "2008-01-07", "2008-01-14", "2008-01-21", "2008-01-28","2008-02-04")
c=c(format(b,"%m-%Y")[1:9])
d=c(NA,NA,NA,NA,NA,4.80, 0.00, 5.04, 3.84)
df=data.frame(a,b,c,d)
df
a b c d
1 1 2007-12-03 12-2007 NA
2 1 2007-12-10 12-2007 NA
3 1 2007-12-17 12-2007 NA
4 1 2007-12-24 12-2007 NA
5 1 2008-01-07 01-2008 NA
6 1 2008-01-14 01-2008 4.80
7 1 2008-01-21 01-2008 0.00
8 1 2008-01-28 01-2008 5.04
9 3 2008-02-04 02-2008 3.84
I tried to do my graph using this:
mplot<-ggplot(df,aes(y=d,x=c))+
geom_bar()+
theme(axis.text.x = element_text(angle=90, vjust=0.5))+
facet_wrap(~ a)
I read from the help of geom_bar():
"geom_bar uses stat_count by default: it counts the number of cases at each x position"
So, I thought it would work like that by I'm having this error:
Error: stat_count() must not be used with a y aesthetic.
For the sample I'm providing, I would like to have the graph for id 1 that shows the months with NA empty and the 01-2008 with 9.84. Then for the second id, I would like to have again the months with NA empty and 02-2008 with 3.84.
I'm also tried to sum the data per month by using aggregate and sum before to plot and then use identity in the stat parameter of geom_bar, but, I'm getting NA in some months and I don't know the reason.
I really aprreciate your help.
You should use geom_col not geom_bar. See the help text:
There are two types of bar charts: geom_bar makes the height of the bar proportional to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col instead. geom_bar uses stat_count by default: it counts the number of cases at each x position. geom_col uses stat_identity: it leaves the data as is.
So your final line of code should be:
ggplot(df, aes(y=d, x=c)) + geom_col() + theme(axis.text.x = element_text(angle=90, vjust=0.5))+facet_wrap(~ a)
Do you want something like this:
mplot = ggplot(df, aes(x = b, y = d))+
geom_bar(stat = "identity", position = "dodge")+
facet_wrap(~ a)
mplot
I am using x = b instead of x = c for now.
No need to use geom_col as suggested by #Jan. Simply use the weight aesthetic instead:
ggplot(iris, aes(Species, weight=Sepal.Width)) + geom_bar() + ggtitle("summed sepal width")

Multiple Plots in R

I want to plot 2 graphs in 1 frame. Basically I want to compare the results.
Anyways, the code I tried is:
plot(male,pch=16,col="red")
lines(male,pch=16,col="red")
par(new=TRUE)
plot(female,pch=16,col="green")
lines(female,pch=16,col="green")
When I run it, I DO get 2 plots in a frame BUT it changes my y-axis. Added my plot below. Anyways, y-axis values are -4,-4,-3,-3,...
It's like both of the plots display their own axis.
Please help.
Thanks
You don't need the second plot. Just use
> plot(male,pch=16,col="red")
> lines(male, pch=16, col = "red")
> lines(female, pch=16, col = "green")
> points(female, pch=16, col = "green")
Note: that will set the frame boundaries based on the first data set, so some data from the second plot could be outside the boundaries of the plot. You can fix it by e.g. setting the limits of the first plot yourself.
For this kind of plot I usually like the plotting with ggplot2 much better. The main reason: It generalizes nicely to more than two lines without a lot of code.
The drawback for your sample data is that it is not available as a data.frame, which is required for ggplot2. Furthermore, in every case you need a x-variable to plot against. Thus, first let us create a data.frame out of your data.
dat <- data.frame(index=rep(1:10, 2), vals=c(male, female), group=rep(c('male', 'female'), each=10))
Which leaves us with
> dat
index vals group
1 1 -0.4334269341 male
2 2 0.8829902521 male
3 3 -0.6052638138 male
4 4 0.2270191965 male
5 5 3.5123679143 male
6 6 0.0615821014 male
7 7 3.6280155376 male
8 8 2.3508890457 male
9 9 2.9824432680 male
10 10 1.1938052833 male
11 1 1.3151289227 female
12 2 1.9956491556 female
13 3 0.8229389822 female
14 4 1.2062726250 female
15 5 0.6633392820 female
16 6 1.1331669670 female
17 7 -0.9002109636 female
18 8 3.2137052284 female
19 9 0.3113656610 female
20 10 1.4664434215 female
Note that my command assumes you have 10 data values each. That command would have to be adjusted according to your actual data.
Now we may use the mighty power of ggplot2:
library(ggplot2)
ggplot(dat, aes(x=index, y=vals, color=group)) + geom_point() + geom_line()
The call above has three elements: ggplot initializes the plot, tells R to use dat as datasource and defines the plot aesthetics, or better: Which aesthetic properties of the plot (such as color, position, size, etc.) are influenced by your data. We use the x and y-values as expected and furthermore set the color aesthetic to the grouping variable - that makes ggplot automatically plot two groups with different colors. Finally, we add two geometries, that pretty much do what is written above: Draw lines and draw points.
The result:
If you have your data saved in the standard way in R (in a data.frame), you end with one line of code. And if after some thousands years of evolution you want to add another gender, it is still one line of code.

How to set fill alpha in geom_box to number of observation in a factor

I need to draw a set of box plots wherein the data is grouped by factors. I would also like to set the alpha value for each box to represent the number of observations in each factor. The more observations for a given factor, the higher the alpha.
Using the mpg data as an example...
Drawing the plot is straightforward:
library(ggplot2)
ggplot(mpg, aes(x=factor(class), y=displ)) +
geom_boxplot(aes(fill="red", alpha=10)) +
scale_fill_manual(values=c("red"="red"),guide="none") +
scale_alpha(range=c(0,1), guide="none")
And calculating the number of observations for each class is straightforward, using plyr:
ddply(mpg, .(class), nrow)
class V1
1 2seater 5
2 compact 47
3 midsize 41
4 minivan 11
5 pickup 33
6 subcompact 35
7 suv 62
I am sure there is a clever way to do inside of ggplot2, but I have exhausted all ideas.
Thanks!
If you pull the alpha out of the aesthetic (aes), then you can provide the alpha value based on length of each class directly as follows:
ggplot(mpg, aes(x=factor(class), y=displ)) +
geom_boxplot(aes(fill="red"),
alpha = table(mpg$class) / max(table(mpg$class))) +
scale_fill_manual(values=c("red"="red"), guide = "none")
You get this:

Resources