Label error in geom_bar [duplicate] - r

This question already has answers here:
Showing data values on stacked bar chart in ggplot2
(3 answers)
Closed 8 years ago.
I'm trying put label in geom_bar but I can't.
My code
df <- data.frame(
uni = rep(c("D","E","F","G","H"),3),
Var1 = factor(c(rep("A",5),rep("B",5),rep("C",5))),
Freq = c(53.6,50.0,48.5,50.0,56.2,23.2,18.5,27.7,20.0,14.3,23.2,31.5,23.8,30.0,29.6))
df$label = paste(round(df$Freq,0),"%", sep = "")
ggplot(data = df, aes(x = uni, y = Freq, fill = Var1)) +
geom_bar(stat = "identity",position = "fill", width = 1) +
scale_fill_brewer(palette = 3) + geom_text(aes(y = Freq, label = label, position ="identity", face = "bold", size = 1), hjust=0.5, vjust=0.5) +
xlab('') +
ylab('') +
labs(fill = '') +
ggtitle('Example') +
theme(axis.text.y = element_text(size=14,face="bold"), panel.background = element_blank(), plot.title = element_text(size = 20, colour = "black", face = "bold")) +
guides(size=FALSE)

By using ddply from the plyr pacakage, we can create a new variable based on the cumulative sums to get the correct position for each label:
library(plyr)
df <- data.frame(
uni = rep(c("D","E","F","G","H"),3),
Var1 = factor(c(rep("A",5),rep("B",5),rep("C",5))),
Freq = c(53.6,50.0,48.5,50.0,56.2,23.2,18.5,27.7,20.0,14.3,23.2,31.5,23.8,30.0,29.6))
df = ddply(df, .(uni), transform, labPosition = cumsum(Freq)-Freq/2)
df$label = paste(round(df$Freq,0),"%", sep = "")
ggplot(data = df, aes(x = uni, y = Freq, fill = Var1)) +
geom_bar(stat = "identity", width = 1) +
scale_fill_brewer(palette = 3) +
geom_text(aes(y = labPosition, label = label, position ="identity"), hjust=0.5, vjust=0.5, size = 1, face = "bold") +
xlab('') +
ylab('') +
labs(fill = '') +
ggtitle('Example') +
theme(axis.text.y = element_text(size=14,face="bold"), panel.background = element_blank(), plot.title = element_text(size = 20, colour = "black", face = "bold")) +
guides(size=FALSE)
This creates a new variable of the cumulative sum by group, and then subtracts the frequency itself divided by 2 to center it in the middle of that segment.

Related

Why is the themes function not applying changes to the ggplot?

I want to change the text size of my y axis descrption and center my plottitle.
Everything coded within the themes function is not being applied to my graph.
Where is the problem?
finalchart = ggplot(euall,
aes(day, cumulative_cases_of_14_days_per_100000 ,
group = countriesAndTerritories)) +
geom_bar(stat = "identity" ,
col = "white" ,
fill = "darkred") +
facet_wrap("countriesAndTerritories") +
geom_line(aes(y = rollmean(cumulative_cases_of_14_days_per_100000, 1,
na.pad = TRUE),
col = "pink"),
show.legend = FALSE) +
labs(title = "COVID infections in the European Union in September 2020" ,
x = "\nSeptember" ,
y = "Infections per 100'000\n" ,
caption = "source: https://opendata.ecdc.europa.eu/covid19/casedistribution/csv") +
theme(axis.text.y = element_text(size = 5) ,
axis.title.y = element_text(size = 10) ,
plot.title = element_text(hjust = 0.5)) +
theme_minimal()
finalchart
The problem is the order in which you call theme() and theme_minimal(). By calling theme_minimal() second your manual settings in theme() are overwritten.
library(ggplot2)
library(patchwork)
p1 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point() +
ggtitle("theme_minimal second") +
theme(title = element_text(size = 24, color = "red", face = "bold")) +
theme_minimal()
p2 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point() +
ggtitle("theme_minimal first") +
theme_minimal() +
theme(title = element_text(size = 24, color = "red", face = "bold"))
p1+p2

How can I combine multiple ggplot graphs with different dataframes under the same facet?

So, I have the two dataframes that produces two ggplots with the same facet that I want to combine
The first dataframe produces the following ggplot
Dataframe1
library(ggh4x)
library(ggnomics)
library(ggplot2)
library(data.table)
#dataframe
drug <- c("DrugA","DrugB1","DrugB2","DrugB3","DrugC1","DrugC2","DrugC3","DrugC4")
PR <- c(18,430,156,0,60,66,113,250)
GR <- c(16,425,154,0,56,64,111,248)
PS <- c(28,530,256,3,70,76,213,350)
GS <- c(26,525,254,5,66,74,211,348)
group<-c("n=88","n=1910","n=820","n=8","n=252","n=280","n=648","n=1186")
class<-c("Class A","Class B","Class B","Class B","Class C","Class C","Class C","Class C")
df <-data.frame(drug,group, class,PR,GR,PS,GS)
#make wide to long df
df.long <- melt(setDT(df), id.vars = c("drug","group","class"), variable.name = "type")
#Order of variables
df.long$type <- factor(df.long$type, levels=c("PR","GR","PS","GS"))
df.long$class <- factor(df.long$class, levels= c("Class B", "Class A", "Class C"))
df.long$group <- factor(df.long$group, levels= c("n=1910","n=820","n=8","n=88","n=252","n=280","n=648","n=1186"))
df.long$drug <- factor(df.long$drug, levels= c("DrugB1","DrugB2","DrugB3","DrugA","DrugC1","DrugC2","DrugC3","DrugC4"))
Ggplot for dataframe 1
ggplot(df.long, aes(fill = type, x = drug, y = value)) +
geom_bar(aes(fill = type), stat = "identity", position = "dodge", colour="white") +
geom_text(aes(label = value), position = position_dodge(width = 1.2), vjust = -0.5)+
scale_fill_manual(values = c("#fa9fb5","#dd1c77","#bcbddc","756bb1")) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 600)) +
theme(title = element_text(size = 18),
legend.text = element_text(size = 12),
axis.text.x = element_text(size = 9),
axis.text.y =element_text(size = 15),
plot.title = element_text(hjust = 0.5)) +
ggh4x::facet_nested(.~class + group, scales = "free_x", space= "free_x")
This is the 2nd dataframe
#dataframe 2
drug <- c("DrugA","DrugB1","DrugB2","DrugB3","DrugC1","DrugC2","DrugC3","DrugC4")
Sens <- c(0.99,0.97,NA,0.88,0.92,0.97,0.98,0.99)
Spec <- c(1,0.99,1,0.99,0.99,0.99,0.99,1)
class<-c("Class A","Class B","Class B","Class B","Class C","Class C","Class C","Class C")
df2 <-data.frame(drug,class,Sens,Spec)
#wide to long df2
df2.long <- melt(setDT(df2), id.vars = c("drug","class"), variable.name = "type")
#additional variables
df2.long$UpperCI <- c(0.99,0.99,NA,0.98,0.98,0.99,0.99,0.99,1,1,1,1,1,1,1,1)
df2.long$LowerCI <- c(0.97,0.98,NA,0.61,0.83,0.88,0.93,0.97,0.99,0.99,0.99,0.99,0.98,0.99,0.99,0.99)
#order of variables
df2.long$class <- factor(df2.long$class, levels= c("Class B", "Class A", "Class C"))
Ggplot for dataframe 2
ggplot(df2.long, aes(x=drug, y=value, group=type, color=type)) +
geom_line() +
geom_point()+
geom_errorbar(aes(ymin=LowerCI, ymax=UpperCI), width=.2,
position=position_dodge(0.05)) +
scale_y_continuous(labels=scales::percent)+
labs(x="drug", y = "Percentage")+
theme_classic() +
scale_color_manual(values=c('#999999','#E69F00')) +
theme(legend.text=element_text(size=12),
axis.text.x=element_text(size=9),
axis.text.y =element_text(size=15),
panel.background = element_rect(fill = "whitesmoke"))+
facet_wrap(facets = vars(class),scales = "free_x")
So I am trying to combine the two plots under the one facet (the one from dataframe 1), and so far I have done the following
ggplot(df.long)+
aes(x=drug, y=value,fill = type)+
geom_bar(, stat = "identity", position = "dodge", colour="white") +
geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-0.5, size=2) +
scale_fill_manual(breaks=c("PR","GR","PS","GS"),
values=c("#dd1c77","#756bb1","#fa9fb5","#e7e1ef","black","black")) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 1100),sec.axis=sec_axis(~./10, labels = function(b) { paste0(b, "%")},name="Percentage")) + #remove space between x axis labels and bottom of chart
theme(legend.text=element_text(size=12),
legend.position = 'bottom',
axis.text.x=element_text(size=9),
axis.text.y =element_text(size=15),
panel.background = element_rect(fill = "whitesmoke"), #color of plot background
panel.border = element_blank(), #remove border panels of each facet
strip.background = element_rect(colour = NA)) + #remove border of strip
labs(y = "Number of isolates", fill = "")+
geom_errorbar(data=df2.long,aes(x=drug, y=value*1000,ymin=LowerCI*1000, ymax=UpperCI*1000,color=type), width=.2,
position=position_dodge(0.05))+
geom_point(data=df2.long,aes(x=drug,y=value*1000,color=type),show.legend = F)+
geom_line(data=df2.long, aes(x=drug, y=value*1000, group=type, color=type)) +
scale_color_manual(values=c('#999999','#E69F00'))
but I'm stuck on adding the facet from the plot1. I hope anyone can help :)
For this specific case, I don't think the nested facets are the appropriate solution as the n = ... seems metadata of the x-axis group instead of a subcategory of the classes.
Here is how you could plot the data with facet_grid() instead:
ggplot(df.long, aes(drug, value, fill = type)) +
geom_col(position = "dodge") +
geom_text(aes(label = value),
position = position_dodge(0.9),
vjust = -0.5, size = 2) +
geom_errorbar(data = df2.long,
aes(y = value * 1000, color = type,
ymin = LowerCI * 1000, ymax = UpperCI * 1000),
position = position_dodge(0.05), width = 0.2) +
geom_point(data = df2.long,
aes(y = value * 1000, color = type),
show.legend = FALSE) +
geom_line(data = df2.long,
aes(y = value * 1000, group = type, color = type)) +
scale_fill_manual(breaks = c("PR", "GR", "PS", "GS"),
values=c("#dd1c77","#756bb1","#fa9fb5","#e7e1ef","black","black")) +
scale_color_manual(values=c('#999999','#E69F00')) +
scale_y_continuous(expand = c(0, 0), limits = c(0, 1100),
sec.axis = sec_axis(~ ./10,
labels = function(b) {
paste0(b, "%")
}, name = "Percentage")) +
scale_x_discrete(
labels = levels(interaction(df.long$drug, df.long$group, sep = "\n"))
) +
facet_grid(~ class, scales = "free_x", space = "free_x") +
theme(legend.text=element_text(size=12),
legend.position = 'bottom',
axis.text.x=element_text(size=9),
axis.text.y =element_text(size=15),
panel.background = element_rect(fill = "whitesmoke"), #color of plot background
panel.border = element_blank(), #remove border panels of each facet
strip.background = element_rect(colour = NA))
If you insist on including the n = ... labels, perhaps a better way is to add these as text somehwere, i.e. adding the following:
stat_summary(fun = sum,
aes(group = drug, y = stage(value, after_stat = -50),
label = after_stat(paste0("n = ", y))),
geom = "text") +
And setting the y-axis limits to c(-100, 1000) for example.

Add number in a barplot ggplot2 [duplicate]

This question already has an answer here:
Position geom_text on dodged barplot
(1 answer)
Closed 4 years ago.
When adding the percentages to the barplots (see code below), the three percentages that belong to the same "variable" are on the same height, and thus not aligned to their respective bar. How to change that?
#Sum plot
myd<- data.frame( var1 = rep(c("Newly infected","Mortality","TDR level"),each=3),
samp = rep(c("Scen1","Scen2","Scen3"),3),
V3 = c(3.5,2,NA,8,2,NA,4,5,NA)/1.5, V2 = c(3.5,2,NA,8,3,NA,4,4.3,NA), V1 = c(1.5,0.2,5,5,3,0.2,4,-5,2) )
# rshaping data to long form for ggplot2
library(reshape2)
library(ggplot2)
meltd<- melt(myd, id.vars=1:2)
ggplot(meltd, aes(x=var1, y=value, fill=variable)) +
geom_bar(stat="identity",position=position_dodge(width=0.6),width=0.5) +
facet_grid(samp~., switch = "y", scales = "free_y", space = "free") +
theme_bw()+
theme(legend.position = "bottom")+
theme(strip.placement = "outside")+
theme(axis.title.x = element_blank()) +
theme(axis.title.y = element_blank()) +
theme(axis.text.y = element_text(colour="black"))+
theme(strip.text.y = element_text(size = 12, colour = "black"))+
#scale_y_continuous(labels=percent,limits = c(0,1))
coord_flip()+
scale_fill_manual("legend", values = c("V3"="orange","V2" = "red", "V1" = "blue", "Baseline" = "black"))+
geom_text(data=meltd, aes(label=paste0(round(value*100,1),"%"), y=value+0.4*sign(value)), size=4)
Do you mean this?
ggplot(meltd, aes(x = var1, y = value, fill = variable, label = paste0(round(value * 100, 1), "%"))) +
geom_bar(stat = "identity", position = position_dodge(width = 0.6), width = 0.5) +
facet_grid(samp ~ ., switch = "y", scales = "free_y", space = "free") +
coord_flip() +
scale_fill_manual(
"legend",
values = c("V3" = "orange", "V2" = "red", "V1" = "blue", "Baseline" = "black")) +
geom_text(aes(y = value + 0.4 * sign(value)), position = position_dodge(width = 0.6)) +
theme_bw() +
theme(
legend.position = "bottom",
strip.placement = "outside",
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(colour="black"),
strip.text.y = element_text(size = 12, colour = "black"))
Use position = position_dodge(width = 0.6) inside geom_text to dodge labels (equivalent to dodging the bars in geom_bar).

ggplot pie chart choose axes ticks

I would like to know if it's possible to modify the ticks of x axis with a ggplot pie chart.
Here what I can do :
# Some colors
couleurs <- data.frame(
id=seq(1,17,1),
mix=c(c(rep(1,6),rep(2,7),rep(3,4))),
html=c("#A00020","#109618","#388EE4","#C484D1","#FFAA33","#CCCDD0","#004AC5","#F80094","#CB5023","#638995","#33CFCF","#95DC4E","#F7D633","#5C403C","#F72020","#00D96C","#FDE4C5")
)
couleurs$html <- factor(couleurs$html, levels = couleurs$html[order(couleurs$id, decreasing = FALSE)])
# Data
activite <- data.frame(label=c("B to B","B to C","B to B / B to C", "B to B"), cible=c(rep("Externe",3), "Interne"), nb=c(12,9,3,12))
activite$label <- factor(activite$label, levels = activite$label[order(activite$nb[activite$cible=="Externe"], decreasing = TRUE)])
library(plyr)
activite<-ddply(activite,.(cible),transform,pc=(nb/sum(nb))*100)
activite
# Pie chart
library(ggplot2)
ggplot(data = activite, aes(x = "", y = nb, fill = label )) +
geom_bar(stat = "identity", position = position_fill(), width = 1) +
coord_polar(theta= "y", start = 0, direction = -1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white", fontface = "bold", position = position_fill(vjust = 0.5)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey75")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.length = unit(0, "mm")) +
theme(axis.title.x = element_blank(),axis.title.y = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Here my result:
After several hours of serach, I didn't find a solution to create what I want. The exact same pie chart but with personalised ticks like that :
With these particular conditions :
- do not change the direction of the data in the pie chart, I want it like exactly this
- if possible (but if not possible, it's okay), I would like the ticks' labels not superposed with the axis.
If someone can help me, I would really appreciate.
Here's one solution:
ggplot(data = activite %>%
group_by(cible) %>%
arrange(desc(nb)) %>%
mutate(axis.label = cumsum(nb),
axis.position = cumsum(pc)/100) %>%
mutate(axis.label = ifelse(pc == min(pc),
paste(axis.label, "0", sep = "-"),
axis.label)),
aes(x = 1, y = nb, fill = label )) +
geom_segment(aes(x = 1, xend = 1.6, y = axis.position, yend = axis.position),
colour = "grey75") +
geom_vline(xintercept = 1.6, colour = "grey75") +
geom_bar(stat = "identity", position = position_fill(reverse = T), width = 1) +
coord_polar(theta= "y", start = 0, direction = 1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white",
fontface = "bold", position = position_fill(vjust = 0.5, reverse = T)) +
geom_text(aes(x = 1.7, label = axis.label), size = 3,
position = position_fill(reverse = T)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.text = element_blank()) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Explanation:
The sequence in your labels went clockwise, while the direction of the polar coordinates went counter-clockwise. That makes labelling rather troublesome. I switched the direction for polar coordinates, & added reverse = T inside the position adjustment calls for the geoms.
It's hard to assign different axis breaks to different facets of the same plot, so I didn't. Instead, I modified the data to include calculated axis labels / margin positions, added margins via geom_segment / geom_vline, & hid the axis text / ticks in theme().

ggplot2: How to move x-axis up, so it can be under arbitrarily picked bar on horizontal barplot?

I made horizontal barplot. I need to move x-axis up, so it is placed not under the last bar, but under some bar, picked based on other criterion.
I've tried some things, like gtable, but with no success. I would appreciate any help.
This is a picture that illustrats what I want to achieve:
Here is the code to produce sample horizontal barplot:
library("ggplot2")
library("RColorBrewer")
colours <- brewer.pal(11, "RdYlGn")[3:9]
no.names <- 4
name.percentage <- data.frame(name = paste0(LETTERS[1:no.names], letters[1:no.names], sample(LETTERS[1:no.names], size = no.names, replace = TRUE )), percentage = 0.85 + runif(no.names, 0, 0.15))
name.percentage <- rbind(
transform(name.percentage, type = 1, fill = cut(percentage, breaks = c(-Inf,(1:6 * 3 + 81)/100, Inf), right = T, labels = colours)),
transform(name.percentage, percentage = 1 - percentage, type = 2, fill = "#EEEEEE")
)
plot <- ggplot(data = name.percentage,
aes( x = name, y = percentage, fill = fill)) +
geom_bar(stat = "identity", position = "stack", width = 0.75) +
scale_fill_identity(guide = "none") +
labs(x = NULL, y = NULL) +
scale_y_continuous(expand = c(0,0)) +
scale_x_discrete(expand = c(0,0)) +
coord_flip() +
theme_classic() +
theme(axis.ticks.y = element_blank(),
axis.text.y = element_text(size = 11, colour = "black" ),
axis.text.x = element_text(size = 11, colour = "black" ),
axis.line = element_blank(),
plot.margin = grid::unit(c(5,5,5,5),"mm"),
aspect.ratio = ((no.names %% 30) / 30 ) * 1.70)
print(plot)
You could create two separate plots first, removing the axis ticks and labels in one of them entirely:
plot1 <- ggplot(data = subset(name.percentage, name=="AaC" | name=="BbA"),
aes( x = name, y = percentage, fill = fill)) +
geom_bar(stat = "identity", position = "stack", width = 0.75) +
scale_fill_identity(guide = "none") +
labs(x = NULL, y = NULL) +
scale_y_continuous(expand = c(0,0)) +
scale_x_discrete(expand = c(0,0)) +
coord_flip() +
theme_classic() +
theme(axis.ticks.y = element_blank(),
axis.text.y = element_text(size = 11, colour = "black" ),
axis.text.x = element_blank(),
axis.line=element_blank(),
axis.ticks=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
aspect.ratio = ((no.names %% 30) / 30 ) * 1.70)
plot2 <- ggplot(data = subset(name.percentage, name=="CcA" | name=="DdD"),
aes( x = name, y = percentage, fill = fill)) +
geom_bar(stat = "identity", position = "stack", width = 0.75) +
scale_fill_identity(guide = "none") +
labs(x = NULL, y = NULL) +
scale_y_continuous(expand = c(0,0)) +
scale_x_discrete(expand = c(0,0)) +
coord_flip() +
theme_classic() +
theme(axis.ticks.y = element_blank(),
axis.text.y = element_text(size = 11, colour = "black" ),
axis.text.x = element_text(size = 11, colour = "black" ),
axis.line = element_blank(),
aspect.ratio = ((no.names %% 30) / 30 ) * 1.70)
Then you can use plot_grid from package cowplot to arrange the two plots, with align="h" aligning both plots horizontally:
library(cowplot)
plot_grid(plot2, plot1, align="h", ncol=1)

Resources