How to add labels to each bar in the barplot? [duplicate] - r

I would like to do a bar plot outlined in black with percentages inside the bars. Is this possible from qplot? I get the percentages to appear but they don't align with the particular bars.
packages: ggplot2, reshape
x <- data.frame(filename = c("file1", "file2", "file3", "file4"),
low = c(-.05,.06,.07,-.14),
hi = c(.87,.98,.56,.79))
x$tot <- x$hi + x$low
x <- melt(x, id = 'filename')
bar <- qplot(x = factor(filename),
y = value*100,
fill = factor(variable),
data = x,
geom = 'bar',
position = 'dodge') + coord_flip()
bar <- bar + scale_fill_manual(name = '',
labels = c('low',
'Hi',
"Tot"),
values = c('#40E0D0',
'#FF6347',
"#C7C7C7"))
bar <- bar + geom_text(aes(label = value*100))+geom_bar(colour = 'black')
bar <- bar + opts(panel.background = theme_rect(colour = NA))
bar <- bar + opts(legend.justification = 'bottom')
print(bar)

Here you go:
library(scales)
ggplot(x, aes(x = filename, fill = variable)) +
geom_bar(stat="identity", ymin=0, aes(y=value, ymax=value), position="dodge") +
geom_text(aes(x=filename, y=value, ymax=value, label=value,
hjust=ifelse(sign(value)>0, 1, 0)),
position = position_dodge(width=1)) +
scale_y_continuous(labels = percent_format()) +
coord_flip()

This would be a good opportunity for you to start moving away from using qplot, in favor of ggplot. This will be much easier in the long run, trust me.
Here's a start:
library(scales)
ggplot(data = x,aes(x = factor(filename),y = value)) +
geom_bar(aes(fill = factor(variable)),colour = "black",position = 'dodge') +
coord_flip() +
scale_fill_manual(name = '',
labels = c('low',
'Hi',
"Tot"),
values = c('#40E0D0',
'#FF6347',
"#C7C7C7")) +
scale_y_continuous(labels = percent_format())
For philosophical reasons, I will leave the annotation piece to you...

Related

How to label values inside stacked bar graph in R when the y-axis is in percentage

Please help :) I have the following stacked bar graph on R using ggplot.
library (ggplot2)
library(ggthemes)
library(scales)
library(dplyr)
Sweets <- c("Smarties", "Smarties", "Jelly beans", "Jelly beans", "Jelly tots", "Jelly tots", "Astros", "Astros")
Sweet_Colour <- c("Blue","Red", "Blue","Red", "Blue","Red","Blue","Red")
Colour_Quantity <- c(13,14,25,36,96,85,9,12)
df <- data.frame(Sweets, Sweet_Colour, Colour_Quantity)
print (df)
pl <- ggplot(data = df, aes(x = Sweets, y= Colour_Quantity,fill = Sweet_Colour)) + geom_bar(stat="identity", position = "fill") + scale_y_continuous(labels = percent) + ggthemes::theme_tufte() + theme(axis.ticks.x= element_blank(),axis.text.x = element_text(angle = 90, hjust = 0), legend.position="top", text = element_text(size=20))
pl <- pl + labs(x = "\n Sweet Type", y= "Percentage of Blue and Red Sweets \n ")
pl <- pl + scale_fill_discrete(name = "")
pl
1
I would like to add how many blue and red sweets as a label on the stacked graph. I tried to adding the counts to the graph by using geom_text as follows
pl <- pl + geom_text(aes(label = Colour_Quantity), size = 3, position = position_stack(0.5))
but it changes the scale on the y-axis and the graph looks like this instead.
2
Please help me add the colour quantity values onto the stack while keeping the y-axis as a percentage.
When adding labels to a barchart always use the same position for the labels as for the bars, i.e. switch to position_fill in geom_text:
library(ggplot2)
library(ggthemes)
library(scales)
library(dplyr)
pl <- ggplot(data = df, aes(x = Sweets, y = Colour_Quantity, fill = Sweet_Colour)) +
geom_bar(stat = "identity", position = "fill") +
geom_text(aes(label = Colour_Quantity), size = 3, position = position_fill(vjust = .5)) +
scale_y_continuous(labels = percent) +
ggthemes::theme_tufte() +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(angle = 90, hjust = 0),
legend.position = "top", text = element_text(size = 20))
pl <- pl + labs(x = "\n Sweet Type", y = "Percentage of Blue and Red Sweets \n ")
pl <- pl + scale_fill_discrete(name = "")
pl

R ggplot2 with stacked column instead of grouped

I want to plot the data shown below as a grouped bar_plot.
I tried position = "dodge" or position = "dodge2" but it didn't work. Ι also tried position = position_dodge()
It kinda works if i use geom_bar instead of geom_col and remove the y=overlap_percent:
p3 <- ggplot(data = comp_coors, aes(x = species_code, fill = mirna_form)) +
geom_bar(position = "dodge2") + theme_classic()
p3
but i would like the y_axis to have the overlap_percent.
Another attempt which ends in a stacked barplot is:
p2 <- ggplot(data = comp_coors, aes(x = species_code, y = overlap_percent, fill = mirna_form)) +
geom_bar(stat = "identity") + theme_classic()
p2
Finally by using geom_col, it returns this which it doesn't make sense, at least to me:
p4 <- ggplot(data = comp_coors, aes(x = species_code, y = overlap_percent, fill = mirna_form)) +
geom_col(position = "dodge") + theme_classic()
p4
The data that i want to plot :
comp_coors <- data.table( species = c("aae","cel", "dme","hsa", "mdo"),
mirna_form = c("mature", "precursor"),
overlap_percent = c(100.0, 100.0, 88.0, 95.5, 91.7, 100.0, 96.6, 98.4),
overlapping_attribute = c("ID=MIMAT0014285;Alias=MIMAT0014285", "ID=MI0000043;Alias=MI0000043;Name=cel-mir-72", "ID=MIMAT0000401;Alias=MIMAT0000401;Name=dme-miR-", "ID=MI0000791;Alias=MI0000791;Name=hsa-mir-383", "ID=MI0005331;Alias=MI0005331;Name=mdo-let-7g")
)
Try using species as a factor and add stat = "identity" like this:
ggplot(data = comp_coors, aes(x = factor(species), y = overlap_percent, fill = mirna_form)) +
geom_bar(position = "dodge", stat = "identity") + theme_classic() + labs(x = "Species", y = "Overlap percent")
Output:
A grouped barplot with overlap_percent on y-axis right.

Why do two legends appear when manually editing in ggplot2?

I want to plot two lines, one solid and another one dotted, both with different colors. I'm having trouble dealing with the legends for this plot. Take this example:
library(ggplot2)
library(reshape2)
df = data.frame(time = 0:127,
mean_clustered = rnorm(128),
mean_true = rnorm(128)
)
test_data_long <- melt(df, id="time") # convert to long format
p = ggplot(data=test_data_long,
aes(x=time, y=value, colour=variable)) +
geom_line(aes(linetype=variable)) +
labs(title = "", x = "Muestras", y = "Amplitud", color = "Spike promedio\n") +
scale_color_manual(labels = c("Hallado", "Real"), values = c("blue", "red")) +
xlim(0, 127)
print(p)
Two legends appear, and on top of it, none of them is correct (the one with the right colors has wrong line styles, and the one with the right line styles has all other things wrong).
Why is this happening and how can I get the right legend to appear?
You need to ensure all the aesthetic mappings match between the different aesthetics you're using:
library(ggplot2)
library(reshape2)
data.frame(
time = 0:127,
mean_clustered = rnorm(128),
mean_true = rnorm(128)
) -> xdf
test_data_long <- melt(xdf, id = "time")
ggplot(
data = test_data_long,
aes(x = time, y = value, colour = variable)
) +
geom_line(aes(linetype = variable)) +
scale_color_manual(
name = "Spike promedio\n", labels = c("Hallado", "Real"), values = c("blue", "red")
) +
scale_linetype(
name = "Spike promedio\n", labels = c("Hallado", "Real")
) +
labs(
x = "Muestras", y = "Amplitud", title = ""
) +
xlim(0, 127)
Might I suggest also using theme parameters to adjust the legend title:
ggplot(data = test_data_long, aes(x = time, y = value, colour = variable)) +
geom_line(aes(linetype = variable)) +
scale_x_continuous(name = "Muestras", limits = c(0, 127)) +
scale_y_continuous(name = "Amplitud") +
scale_color_manual(name = "Spike promedio", labels = c("Hallado", "Real"), values = c("blue", "red")) +
scale_linetype(name = "Spike promedio", labels = c("Hallado", "Real")) +
labs(title = "") +
theme(legend.title = element_text(margin = margin(b=15)))

Adding labels to ggplot bar chart

I would like to do a bar plot outlined in black with percentages inside the bars. Is this possible from qplot? I get the percentages to appear but they don't align with the particular bars.
packages: ggplot2, reshape
x <- data.frame(filename = c("file1", "file2", "file3", "file4"),
low = c(-.05,.06,.07,-.14),
hi = c(.87,.98,.56,.79))
x$tot <- x$hi + x$low
x <- melt(x, id = 'filename')
bar <- qplot(x = factor(filename),
y = value*100,
fill = factor(variable),
data = x,
geom = 'bar',
position = 'dodge') + coord_flip()
bar <- bar + scale_fill_manual(name = '',
labels = c('low',
'Hi',
"Tot"),
values = c('#40E0D0',
'#FF6347',
"#C7C7C7"))
bar <- bar + geom_text(aes(label = value*100))+geom_bar(colour = 'black')
bar <- bar + opts(panel.background = theme_rect(colour = NA))
bar <- bar + opts(legend.justification = 'bottom')
print(bar)
Here you go:
library(scales)
ggplot(x, aes(x = filename, fill = variable)) +
geom_bar(stat="identity", ymin=0, aes(y=value, ymax=value), position="dodge") +
geom_text(aes(x=filename, y=value, ymax=value, label=value,
hjust=ifelse(sign(value)>0, 1, 0)),
position = position_dodge(width=1)) +
scale_y_continuous(labels = percent_format()) +
coord_flip()
This would be a good opportunity for you to start moving away from using qplot, in favor of ggplot. This will be much easier in the long run, trust me.
Here's a start:
library(scales)
ggplot(data = x,aes(x = factor(filename),y = value)) +
geom_bar(aes(fill = factor(variable)),colour = "black",position = 'dodge') +
coord_flip() +
scale_fill_manual(name = '',
labels = c('low',
'Hi',
"Tot"),
values = c('#40E0D0',
'#FF6347',
"#C7C7C7")) +
scale_y_continuous(labels = percent_format())
For philosophical reasons, I will leave the annotation piece to you...

Annotation above bars:

dodged bar plot in ggplot again has me stumped. I asked about annotating text above bars on here a few weeks back (LINK) and got a terrific response to use + stat_bin(geom="text", aes(label=..count.., vjust=-1)). I figured since I already have the counts I'll just supply them with out the .. before and after and I told stat_bin that the position was dodge. It lines them up over the center of the group and adjusts up and down. Probably something minor. Please help me to get the text over the bars.
mtcars2 <- data.frame(type=factor(mtcars$cyl),
group=factor(mtcars$gear))
library(plyr); library(ggplot)
dat <- rbind(ddply(mtcars2,.(type,group), summarise,
count = length(group)),c(8,4,NA))
p2 <- ggplot(dat,aes(x = type,y = count,fill = group)) +
geom_bar(colour = "black",position = "dodge",stat = "identity") +
stat_bin(geom="text", aes(position='dodge', label=count, vjust=-.6))
I was having trouble getting the position dodges to line up, so I ended up creating a position_dodge object (is that the right terminology?), saving it to a variable, and then using that as the position for both geoms. Somewhat infuriatingly, they still seem to be a little off centre.
dodgewidth <- position_dodge(width=0.9)
ggplot(dat,aes(x = type,y = count, fill = group)) +
geom_bar(colour = "black", position = dodgewidth ,stat = "identity") +
stat_bin(geom="text", position= dodgewidth, aes(x=type, label=count), vjust=-1)
Updated geom_bar() needs stat = "identity"
I think this does what you want as well.
mtcars2 <- data.frame(type = factor(mtcars$cyl), group = factor(mtcars$gear))
library(plyr); library(ggplot2)
dat <- rbind(ddply(mtcars2, .(type, group), summarise, count = length(group)), c(8, 4, NA))
p2 <- ggplot(dat, aes(x = type,y = count,fill = group)) +
geom_bar(stat = "identity", colour = "black",position = "dodge", width = 0.8) +
ylim(0, 14) +
geom_text(aes(label = count, x = type, y = count), position = position_dodge(width = 0.8), vjust = -0.6)
p2

Resources