Waffle Bar Chart with scale - r

I'm trying to recreate this waffle bar chart: https://github.com/hrbrmstr/waffle#waffle-bar-charts-with-scales
library(dplyr)
library(waffle)
storms %>%
filter(year >= 2010) %>%
count(year, status) -> storms_df
ggplot(storms_df, aes(fill = status, values = n)) +
geom_waffle(color = "white", size = .25, n_rows = 10, flip = TRUE) +
facet_wrap(~year, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_y_continuous(labels = function(x) x * 10, # make this multiplyer the same as n_rows
expand = c(0,0)) +
ggthemes::scale_fill_tableau(name=NULL) +
coord_equal() +
labs(
title = "Faceted Waffle Bar Chart",
subtitle = "{dplyr} storms data",
x = "Year",
y = "Count"
) +
theme_minimal(base_family = "Roboto Condensed") +
theme(panel.grid = element_blank(), axis.ticks.y = element_line()) +
guides(fill = guide_legend(reverse = TRUE))
And it seems that geom_waffle is no longer available, it's waffle now and they changed some arguments as well.
So I created a named vector and fixed the color argument, but it's still not working:
storms %>%
filter(year >= 2010) %>%
count(status) -> storms_df2
vec = extract2(storms_df2, 'n') %>% set_names(storms_df2$status)
ggplot(storms_df, aes(fill = status, values = n)) +
waffle(vec,colors=c("red","green","blue"), size = .25, rows = 10, flip = TRUE) +
facet_wrap(~year, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_y_continuous(labels = function(x) x * 10, # make this multiplyer the same as n_rows
expand = c(0,0)) +
ggthemes::scale_fill_tableau(name=NULL) +
coord_equal() +
labs(
title = "Faceted Waffle Bar Chart",
subtitle = "{dplyr} storms data",
x = "Year",
y = "Count"
) +
theme_minimal(base_family = "Roboto Condensed") +
theme(panel.grid = element_blank(), axis.ticks.y = element_line()) +
guides(fill = guide_legend(reverse = TRUE))
What am I missing? The waffle funstion on it's own is working, but I need a bar chart by year:
waffle(vec, rows = 50, colors=c("red","green","blue"))

If you'll install waffle from this repository you'll be able to create this chart
install.packages("waffle", repos = "https://cinc.rud.is")
library(tidyverse)
library(waffle)
library(ggthemes)
storms %>%
filter(year >= 2010) %>%
count(year, status) -> storms_df
ggplot(storms_df, aes(fill = status, values = n)) +
geom_waffle(color = "white", size = .25, rows = 10, flip = TRUE) +
facet_wrap(~year, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_y_continuous(labels = function(x) x * 10, # make this multiplyer the same as n_rows
expand = c(0,0)) +
ggthemes::scale_fill_tableau(name=NULL) +
coord_equal() +
labs(
title = "Faceted Waffle Bar Chart",
subtitle = "Created by Anil Goyal",
x = "Year",
y = "Count"
) +
theme_minimal(base_family = "Roboto Condensed") +
theme(panel.grid = element_blank(), axis.ticks.y = element_line()) +
guides(fill = guide_legend(reverse = TRUE))
I have changed the subtitle just to show that it is still working.

Related

Replace x axis labels with colored bars to get a gradient effect in R

I'm building a barplot with RNA reads % in ggplot, I did this:
ggplot(tipos_exo,aes(x = reorder(sample, -value),y = value,fill = variable)) +
geom_bar( stat = "identity")
I need to replace the x axis labels with colored bars, each sample belongs to a specific batch and I looking for this effect:
Any thoughts?
One option to achieve your desired result would be to create your axis colorbar as a second plot and glue it to the main plot via the patchwork package.
For the colorbar I use geom_tile and remove all non-data ink using theme_void. As a first step I reorder your sample column by value and get rid of the duplicated sample categories using dplyr::distinct.
Using some fake random example data:
set.seed(123)
tipos_exo <- data.frame(
sample = rep(letters, each = 2),
variable = c("tablaq_readsPerc", "tablaq_shortReadsPerc"),
value = runif(52, 0, 100),
batch = rep(LETTERS, each = 2)
)
library(ggplot2)
library(patchwork)
library(dplyr, warn = FALSE)
p1 <- ggplot(tipos_exo,aes(x = reorder(sample, -value),y = value,fill = variable)) +
geom_bar( stat = "identity") +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.length.x = unit(0, "pt"))
tipos_exo1 <- tipos_exo |>
mutate(sample = reorder(sample, -value)) |>
distinct(sample, batch)
p_axis <- ggplot(tipos_exo1, aes(x = sample, y = factor(1), fill = batch)) +
geom_tile(width = .9) +
geom_text(aes(label = sample)) +
theme_void() +
theme(axis.title.x = element_text()) +
labs(x = "Batch Annotation") +
guides(fill = "none")
p1 / p_axis + plot_layout(heights = c(8, 1))
UPDATE Adapting my answer on this post Reorder Bars of a Stacked Barchart in R you could reorder your sample column by a helper value "column", e.g. if you want to reorder by "tablaq_readsPerc" you set the values for the other categories to zero and use FUN=sum. Note that I also reversed the order of the stack so that the "tablaq_readsPerc" bars are placed at the bottom.
tipos_exo <- tipos_exo |>
mutate(sample1 = reorder(sample, -ifelse(!variable %in% "tablaq_readsPerc", 0, value), FUN = sum))
p1 <- ggplot(tipos_exo,aes(x = sample1, y = value, fill = variable)) +
geom_bar( stat = "identity", position = position_stack(reverse = TRUE)) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.length.x = unit(0, "pt"))
tipos_exo1 <- tipos_exo |>
distinct(sample, sample1, batch)
p_axis <- ggplot(tipos_exo1, aes(x = sample1, y = factor(1), fill = batch)) +
geom_tile(width = .9) +
geom_text(aes(label = sample)) +
theme_void() +
theme(axis.title.x = element_text()) +
labs(x = "Batch Annotation") +
guides(fill = "none")
p1 / p_axis + plot_layout(heights = c(8, 1))

How to add labels to a stacked bar graph

I am looking to add numerical values to the middle of each stack in the stacked bar graph (code below). Most of the examples I am finding are orientated towards information in one column and whenever I try to modify it, I run into errors about length requirements.
DA <- data.frame(
Imp=c("2015","2019"),
"mismatch"=c(220,209),
"match"=c(3465,3347),
"NA"=c(501,630),
check.names = FALSE)
DA %>%
pivot_longer(-Imp) %>%
ggplot(aes(x = Imp, y = value, fill = name)) + geom_col(position = "stack") +
scale_fill_manual(name=" ", values=c("aquamarine4", "orange", "coral")) +
theme_light() +
theme(legend.position = "bottom") +
scale_y_continuous(expand = c(0,0)) +
geom_text(aes(x=1, y=4300, label="Stretch it"), vjust=-1) +
labs(y="Count", x="Imputed Genotypes") +
geom_bar(stat = "identity", color="white", width = 1)
Like this?
library(tidyverse)
DA <- data.frame(
Imp=c("2015","2019"),
"mismatch"=c(220,209),
"match"=c(3465,3347),
"NA"=c(501,630),
check.names = FALSE)
DA %>%
pivot_longer(-Imp) %>%
ggplot(aes(x = Imp, y = value, fill = name)) +
geom_col(color = "white", lwd = 1,
position = "stack", width = 0.75) +
scale_fill_manual(name="", values=c("aquamarine4", "orange", "coral")) +
scale_y_continuous(expand = c(0,0),
limits = c(0, 4200)) +
labs(y="Imputed Genotypes (Count)") +
geom_text(aes(label = value), color = "white", size = 5,
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
theme_light(base_size = 18) +
theme(legend.position = "right",
axis.title.x = element_blank())
Created on 2021-12-19 by the reprex package (v2.0.1)

How to do a pie chart with two factor variables and % inside the plot

How can I transform this bar plot into a pie chart?
This is the bar plot I have:
This is the code I use to make the bar plot:
dados_gráfico_distrito <- dados_desde_2015 %>%
filter(!is.na(qsd_distrito_nascimento_rec)) %>%
group_by(anoletivo_cat) %>%
count(anoletivo_cat, qsd_distrito_nascimento_rec) %>%
mutate(pct = n / sum(n), pct_label = scales::percent(pct, accuracy=1))
dados_gráfico_distrito$qsd_distrito_nascimento_rec <- factor(dados_gráfico_distrito$qsd_distrito_nascimento_rec, levels = c("Other", "Porto", "Braga"))
ggplot(dados_gráfico_distrito, aes(x= anoletivo_cat, fill = qsd_distrito_nascimento_rec, y = pct)) +
geom_bar(position = "fill", stat="identity", width = 0.5) +
geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme_void() + scale_fill_brewer(palette="Paired") +
theme(legend.text = element_text(size = 8, colour = "black")) +
theme(axis.text = element_text(size = 8, colour = "black")) +
theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
When I try to transform it in a pie chart, adding the code line coord_polar () I get this chart:
This is what I pretend:
Thank you!
As you did not provide sample data, I have used some other sample data. Perhaps this will meet your needs. Please modify as necessary.
library(ggrepel)
library (ggplot2)
df = read.csv("https://www.dropbox.com/s/lc3xyuvjjkyeacv/inputpie.csv?dl=1")
df <- df %>% group_by(fac) %>%
mutate(
facc = ifelse(fac=="f1", "15/16 to 19/20", "20/21"),
cs = rev(cumsum(rev(per))),
text_yp = per/2 + lead(cs, 1),
text_yp = if_else(is.na(text_yp), per/2, text_yp)
) %>% data.frame()
df$type <- factor(df$type, levels=unique(df$type))
ggplot(df, aes(x="", y=per, fill=type )) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
facet_grid(facc~. ) +
scale_fill_brewer(palette="Paired") +
theme_void() +
geom_label_repel(
aes(label = text_y, y = text_yp), show.legend = FALSE
) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme(legend.text = element_text(size = 8, colour = "black")) +
#theme(axis.text = element_text(size = 8, colour = "black")) +
#theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))

Issue filling histogram in ggplot

I am trying to fill with the same colour as the lines the data of the histograms shown in the figure below, I am using the following code. I have tried many things using fill, scale_fill_manual but without success. Any idea in how to correct this?
(stations = unique(DSF_moments$Station))
(station_cols = scales::hue_pal()(length(stations)))
(names(station_cols) = sort(stations))
for (i in 1:length(listDF2))
{
df1 <- as.data.frame(listDF2[[i]])
df1[is.na(df1)] <- 0
plot1 <- ggplot(df1, aes(x = Date, y = DailyMeanStreamflow, colour=Station)) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Daily Mean Streamflow", y = "Q[m3/s/Day]", x = "Date") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_color_manual(values = station_cols)
plot2 <- ggplot(df1, aes(DailyMeanStreamflow, colour=Station)) +
geom_histogram(show.legend = FALSE) +
labs(title = "Daily Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Day]")+
scale_colour_manual(values = station_cols) + scale_fill_manual(values = station_cols)
(Monthly_Streamflow_Station <- df1 %>% group_by(month) %>% summarise(Monthly_Streamflow_Station = mean(DailyMeanStreamflow, na.rm=TRUE)))
plot3 <- ggplot(Monthly_Streamflow_Station, aes(x = month, y = Monthly_Streamflow_Station, colour=unique(df1$Station))) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Monthly Mean Streamflow", y = "Q[m3/s/Month]", x = "Month") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_x_continuous (breaks=seq(1,12,by=1)) +
scale_color_manual(values = station_cols)
plot4 <- ggplot(Monthly_Streamflow_Station, aes(Monthly_Streamflow_Station, colour=unique(df1$Station))) +
geom_histogram(show.legend = FALSE) +
labs(title = "Monthly Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Month]") +
scale_colour_manual(values = station_cols)
(Annual_Streamflow_Station <- df1 %>% group_by(year) %>% summarise(Annual_Streamflow_Station = mean(DailyMeanStreamflow, na.rm=TRUE)))
plot5 <- ggplot(Annual_Streamflow_Station, aes(x = year, y = Annual_Streamflow_Station, colour=unique(df1$Station))) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Annual Mean Streamflow", y = "Q[m3/s/Year]", x = "Year") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_color_manual(values = station_cols)
plot6 <- ggplot(Annual_Streamflow_Station, aes(Annual_Streamflow_Station,colour=unique(df1$Station))) +
geom_histogram(show.legend = FALSE) +
labs(title = "Annual Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Year]") +
scale_colour_manual(values = station_cols)
grid.arrange(grobs=list(plot1, plot2, plot3, plot4, plot5, plot6), ncol = 2, nrow = 3)
name5<- paste("Plots","_", siteNumber[i], ".png", sep="")
g <- arrangeGrob(plot1, plot2, plot3, plot4, plot5, plot6, ncol = 2, nrow = 3)
ggsave(g,filename = name5,width=22,height=11,units="in",dpi=500)
dev.off()
}
Try this change on your loop. No output produced due to lack of data. I have also changed scale_color_*() by scale_fill_*() where necesssary as said by great #aosmith that histograms require filling option enabled:
#Code
for (i in 1:length(listDF2))
{
df1 <- as.data.frame(listDF2[[i]])
df1[is.na(df1)] <- 0
plot1 <- ggplot(df1, aes(x = Date, y = DailyMeanStreamflow, colour=Station)) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Daily Mean Streamflow", y = "Q[m3/s/Day]", x = "Date") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_color_manual(values = station_cols)
plot2 <- ggplot(df1, aes(DailyMeanStreamflow, fill=Station)) +
geom_histogram(show.legend = FALSE) +
labs(title = "Daily Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Day]")+
scale_fill_manual(values = station_cols)
(Monthly_Streamflow_Station <- df1 %>% group_by(month) %>% summarise(Monthly_Streamflow_Station = mean(DailyMeanStreamflow, na.rm=TRUE)))
plot3 <- ggplot(Monthly_Streamflow_Station, aes(x = month, y = Monthly_Streamflow_Station, colour=unique(df1$Station))) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Monthly Mean Streamflow", y = "Q[m3/s/Month]", x = "Month") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_x_continuous (breaks=seq(1,12,by=1)) +
scale_color_manual(values = station_cols)
plot4 <- ggplot(Monthly_Streamflow_Station,
aes(Monthly_Streamflow_Station,
fill=unique(df1$Station))) +
geom_histogram(show.legend = FALSE) +
labs(title = "Monthly Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Month]") +
scale_fill_manual(values = station_cols)
(Annual_Streamflow_Station <- df1 %>% group_by(year) %>% summarise(Annual_Streamflow_Station = mean(DailyMeanStreamflow, na.rm=TRUE)))
plot5 <- ggplot(Annual_Streamflow_Station, aes(x = year, y = Annual_Streamflow_Station, colour=unique(df1$Station))) +
geom_line(size = 1, show.legend = FALSE) +
geom_point(size=1.5, shape=21, fill="white",na.rm = TRUE, show.legend = FALSE)+
labs(title = "Annual Mean Streamflow", y = "Q[m3/s/Year]", x = "Year") +
theme(plot.title = element_text(size=16), axis.text.y = element_text(size=11), axis.text.x = element_text(size=11)) +
scale_color_manual(values = station_cols)
plot6 <- ggplot(Annual_Streamflow_Station,
aes(Annual_Streamflow_Station,
fill=unique(df1$Station))) +
geom_histogram(show.legend = FALSE) +
labs(title = "Annual Mean Streamflow Histogram", y = "Frequency", x="Q[m3/s/Year]") +
scale_fill_manual(values = station_cols)
grid.arrange(grobs=list(plot1, plot2, plot3, plot4, plot5, plot6), ncol = 2, nrow = 3)
name5<- paste("Plots","_", siteNumber[i], ".png", sep="")
g <- arrangeGrob(plot1, plot2, plot3, plot4, plot5, plot6, ncol = 2, nrow = 3)
ggsave(g,filename = name5,width=22,height=11,units="in",dpi=500)
dev.off()
}

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.

Resources