Dividing a chart in two parts - r

I have the code of two graphs that I want to separate into two. I would like to see half of these results on one graph and the other half on another since the current plot contains too much information. Here is the code for my charts:
Medellin7 <- Medellin4 %>%
filter(Medellin4$AÑO_T %in% c("2019"))
Medellin7
Medellin8 <- Medellin7 %>%
filter(Medellin7$MES_TURNO %in% c("06"))
Medellin8
ATENCIONFUNCIONARIO <- Medellin8 %>%
group_by(NOMBRE_SERVICIO, NOMBRE, NOMBRE_SERVICIO) %>%
summarize(TIEMPO = mean(TIEMPO)) %>%
ungroup() %>%
mutate(NOMBRE_SERVICIO = factor(NOMBRE_SERVICIO, levels = unique(NOMBRE_SERVICIO)),
NOMBRE = as.factor(NOMBRE))
# First Chart
grafico5 <- ggplot(data = ATENCIONFUNCIONARIO,
aes(x = NOMBRE_SERVICIO, y = TIEMPO, group = NOMBRE, colour = NOMBRE)) +
xlab("SERVICIO") + ylab("CANTIDAD") +
ggtitle("TIEMPO PROMEDIO ATENCIÓN FUNCIONARIO")+
theme(axis.text.x=element_text(angle=90,hjust=1)) +
theme(plot.title = element_text(hjust = 0.5))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "white"))+
geom_line(lwd=1)
grafico5
Second Chart:
FUNCIONARIO <- Medellin1 %>%
group_by(AÑO_T, NOMBRE) %>%
summarise(TIEMPO = length(TIEMPO))
FUNCIONARIO <- FUNCIONARIO\[order(FUNCIONARIO$NOMBRE, decreasing = TRUE),\]
M<- ggplot(FUNCIONARIO, aes(factor(NOMBRE), TIEMPO, fill = factor(AÑO_T))) +
geom_bar(stat="identity", position="dodge")+
theme(axis.text.x=element_text(angle=90,hjust=1))+
xlab("MES")+
ylab("CANTIDAD")+
labs(fill="AÑO")+
ggtitle("DEMANDA MES")+
theme(plot.title = element_text(hjust = 0.5))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "gray"))]

Splitting the plot into two identical plots seems like a strange choice. One alternative would be to use facet_wrap using Nombre as the facet variable. This would give you a clear look at each line in the chart. Your code would look something like this:
grafico5 <- ggplot(data = ATENCIONFUNCIONARIO,
aes(x = NOMBRE_SERVICIO, y = TIEMPO)) +
xlab("SERVICIO") + ylab("CANTIDAD") +
ggtitle("TIEMPO PROMEDIO ATENCIÓN FUNCIONARIO")+
theme(axis.text.x=element_text(angle=90,hjust=1)) +
theme(plot.title = element_text(hjust = 0.5))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "white"))+
geom_line(lwd=1) +
facet_wrap(~Nombre)
Here's a reproducible example:
data(iris)
library(ggplot2)
ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) +
geom_line() +
facet_wrap(~Species)
Which gives you:

Related

How to plot counts stackbar in ggplot2 R?

Dataset contains "two friends" and coded "interaction" (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.
Friend1 <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Friend2 <- c("1","1","2","2","1","1","2","2","1","1","2","2","1","1","2","2")
Interaction <- c("O","X","D","D","D","X","X","D/R","O","X","D","D","D","X","X","D/R")
df <- data.frame(Friend1, Friend2, Interaction)
df$Friend1 <- as.factor(as.character(df$Friend1))
df$Friend2 <- as.factor(as.character(df$Friend2))
df$Interaction <- as.factor(as.character(df$Interaction))
ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2)) +
geom_bar(position="fill", stat="identity", color = "white") + theme_classic() + theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size=1)) + theme(strip.background = element_blank()) + facet_grid(.~Friend1)
Erorr: Error in UseMethod("count") :
no applicable method for 'count' applied to an object of class "character"
How do I "count" these factors to visualize frequency of interactions?
The issue is that dplyr::count expects a dataframe as its first argument and returns a dataframe. However, there is no reason to compute the counts as geom_bar will do that by default, i.e. get rid of y=... and stat="identity":
library(ggplot2)
ggplot(df, aes(fill = Interaction, x = Friend2)) +
geom_bar(position = "fill", color = "white") +
theme_classic() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size = 1)
) +
theme(strip.background = element_blank()) +
facet_grid(. ~ Friend1)
An alternative visualization using facets per "friends" column may make your counts clearer than a standard stacked bar:
ggplot(df, aes(x = 1, fill = Interaction)) +
geom_bar(width = 1, color = "white", size = 1, alpha = 0.8) +
geom_text(stat = "count", aes(label = after_stat(count)), size = 7,
position = position_stack(vjust = 0.5), color = "white",
fontface = 2) +
facet_grid(Friend1 ~ Friend2, switch = "both") +
scale_fill_brewer(palette = "Set1") +
coord_polar(theta = "y") +
labs(x = "Friend1", y = "Friend2") +
theme_bw(base_size = 20) +
theme(panel.grid = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
axis.text.x = element_blank(),
panel.border = element_rect(color = "gray90", fill = NA),
panel.spacing = unit(0, "mm"),
axis.text = element_blank(),
axis.ticks = element_blank())

Formatting facet pie chart ggplot

I have a sample data frame as follows:
set.seed(87)
df = data.frame(
sample = rep(c("PB","PB","BM","BM"),8),
status = rep(c("healthy","myeloma"),16),
family = c(rep("CD4",16),rep("CD8",16)),
phenotype = rep(c("Tn","Tn","Tn","Tn","Tcm","Tcm","Tcm","Tcm","Tem","Tem","Tem","Tem","Temra","Temra","Temra","Temra"),2),
percent = sample(20:30,32,replace=T)
)
I want to plot the data in pie chart format also with faceting in both the x and y axis formatted like this nice diagram I found online:
However I only know how to facet by grouping the two variables (CD4/CD8 and healthy/myeloma) together first with the following code which can't give me the nice separation of the x axis variables into two rows:
df %>%
mutate(group = paste(family,status)) %>%
ggplot(aes(x = "",y=percent,fill = phenotype)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
facet_grid(sample~group) +
theme(axis.text.x=element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank())
Appreciate any ideas on how to make the whole diagram look more like the one online, thanks!
Maybe this is closer -
library(dplyr)
library(ggplot2)
df %>%
mutate(group = paste(family,status)) %>%
ggplot(aes(x = "",y=percent,fill = phenotype)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start=0) +
facet_grid(sample~group) +
theme_classic() +
theme(axis.text.x=element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank(),
strip.background = element_blank(),
strip.text = element_text(size = 15, face = 'bold'),
legend.position="bottom")

barplot with two values on the same column

I have the following graphic:
But I need it to be like this:
My code is:
n_papers<-c(6,4,5,1,6,2,1)
paper_ui<-c(3,2,4,0,1,1,0)
methods<-c("AR","ARMA",'ARIMA',"SARIMA","Loess \n decomposition","Classical \n decomposition","Exponential \n smoothing")
df <- data.frame(n_papers,paper_ui,methods)
ggplot(df) +
aes(x = methods, y = n_papers,fill=paper_ui) +
geom_bar(show.legend = FALSE,stat="identity",position = "dodge")+
labs(x=NULL, y = "Number of papers") +
theme_bw()+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))
And I need the blue to be the same to all the bars color="dodgerblue4". Thank you for the help!
You could add a second geom_bar or geom_col like so:
library(ggplot2)
ggplot(df) +
aes(x = methods) +
geom_col(aes(y = n_papers, fill = "total"))+
geom_col(aes(y = paper_ui, fill = "ui"))+
labs(x=NULL, y = "Number of papers") +
scale_fill_manual(values = c(total = "grey", ui = "dodgerblue4")) +
theme_bw()+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))

geom_text labelling bars incorrectly

I am trying to create a graph in R with ggplot. The graph is fine until I try to add labels with geom_text.
Data:
year <-c(2016,2017,2016,2017,2016,2017,2016,2017,2016,2017,2016,2017,2016,2017)
age <- c("0-15","0-15","16-25","16-25","26-35","26-35","36-45","36-45","46-55","46-55","56-65","56-65","66+","66+")
deaths <- c(10,4,40,33,38,28,23,22,18,22,13,16,44,33)
age_group <- factor(age)
fyear <- factor(year)
ideaths <- data.frame(fyear,age_group,deaths)
This is the code I have so far
ggplot(data = ideaths,mapping = aes(x = age_group, y=deaths,
fill=fyear)) +
geom_bar(position = "dodge", stat="identity", width=0.5) +
geom_text(label=deaths,vjust=-0.5) + ggtitle("Figure 8.") +
scale_fill_manual(values=c("#7F7F7F","#94D451")) +
scale_y_continuous(breaks=seq(0,55,5)) + theme_light() +
theme(panel.border = element_blank(), panel.grid.major.x =
element_blank(), panel.grid.minor.y =
element_blank(),panel.grid.major.y = element_line( size=.1,
color="grey"), axis.title = element_blank(), legend.position
= "bottom", legend.title=element_blank(), plot.title
=element_text(size=10))
Which gives me this graph:
I searched for how to align the labels with the bars and found position=position_dodge(width=0.9)
However, this puts the label over the wrong bar for me.
If anyone has any idea of how to fix this, or what is causing it in the first place it would be greatly appreciated!
You need to put label = deaths inside aes() so ggplot knows that it needs to use the deaths column inside ideaths data frame not the standalone deaths vector
library(ggplot2)
ggplot(data = ideaths, aes(x = age_group, y = deaths, fill = fyear)) +
geom_col(position = position_dodge(width = 0.9)) +
geom_text(aes(x = age_group, y = deaths + 3, label = deaths),
position = position_dodge(width = 0.9)) +
ggtitle("Figure 8.") +
scale_fill_manual(values = c("#7F7F7F", "#94D451")) +
scale_y_continuous(breaks = seq(0, 55, 5)) +
theme_light() +
theme(
panel.border = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_line(size = .1, color = "grey"),
axis.title = element_blank(), legend.position = "bottom",
legend.title = element_blank(), plot.title = element_text(size = 10)
)
Created on 2018-11-19 by the reprex package (v0.2.1.9000)

Subscript and width restrictions in x-axis tick labels in ggplot2

This is currently my code for the figure above
ggplot(AllData, aes(Year, AGResiduals, fill=Type)) +
geom_boxplot(outlier.size=0) +
scale_fill_manual(values=c("skyblue4", "skyblue"),
name="Male Type",
labels=c("Guarders","Sneakers")) +
labs(x=NULL, y = "Residual of Accessory Gland Mass x Total Mass") +
scale_x_discrete(limits=c("2007","2008","2010","2011","2013","2014","2015"),
labels=str_wrap(c("2007 (nG=37, nS=8)","2008 (nG=4, nS=6)","2010 (nG=31, nS=6)","2011 (nG=55, nS=5)","2013 (nG=202, nS=24)","2014 (nG=63)","2015 (nG=59, nS=3)"),
width=6)) +
theme(plot.title = element_text(size = rel(1.4)),
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.5)),
axis.text.y = element_text(size = rel(1.5)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))
I want to make the "G" and "S"'s in each x-axis tick labels subscript (they designate sample size for two different groups, G and S).
Writing
expression(2007 (n[G]=37, n[S]=8)
works, but only if I remove the preceding
str_wrap
code for some reason.
I need to constrain the width of the text for each x-axis tick label, so I need to retain str_wrap or use line breaks within the expression function somehow.
I also can't replace my list of labels with a factor since I have to set limits on the years I want to show.
Can someone please help on how to make a 3-line x-axis tick label that allows for subscript?
I couldn't find a way to display expressions on multiple lines, but you could try rotating the labels:
library(stringr)
library(ggplot2)
library(scales)
library(dplyr)
n <- 100
y <- as.character(sample(2007:2015,n,replace=T))
t <- sample(c("Guarders","Guarders","Sneakers"),n,replace=T)
r <- rnorm(n,10,20)
nsk <- sum(t=="Sneakers")
r[ t=="Sneakers" ] <- rnorm(nsk,1,5)
AllData <- data.frame(Year=y,AGResiduals=r,Type=t)
sdf <- AllData %>% group_by( Year ) %>%
summarize( n=n(), ng=sum(Type=="Guarders") )
fmts <- rep("%s (n[G]==%d) ~~ (n[S]==%d)",nrow(sdf))
labs2 <- do.call(sprintf,list(fmts,sdf$Year,sdf$ng, sdf$n-sdf$ng ) )
ex2 <- parse(text=labs2)
ggplot(AllData, aes(Year, AGResiduals, fill=Type)) +
geom_boxplot(outlier.size=0) +
scale_fill_manual(values=c("skyblue4", "skyblue"),
name="Male Type",
labels=c("Guarders","Sneakers")) +
labs(x=NULL, y = "Residual of Accessory Gland Mass x Total Mass") +
scale_x_discrete(limits=c("2007","2008","2010","2011","2013","2014","2015"),
labels=ex2) +
theme(plot.title = element_text(size = rel(1.4)),
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.0),angle=-30,hjust=0),
axis.text.y = element_text(size = rel(1.5)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))
Yields this:
Rawr made a suggestion that allows you to get two, but not three lines. Since it doesn't require rotation, I am entering it as a second solution.
This:
library(stringr)
library(ggplot2)
library(scales)
library(dplyr)
set.seed(23456)
n <- 100
y <- as.character(sample(2007:2015,n,replace=T))
t <- sample(c("Guarders","Guarders","Sneakers"),n,replace=T)
r <- rnorm(n,10,20)
nsk <- sum(t=="Sneakers")
r[ t=="Sneakers" ] <- rnorm(nsk,1,5)
AllData <- data.frame(Year=y,AGResiduals=r,Type=t)
sdf <- AllData %>% group_by( Year ) %>%
summarize( n=n(), ng=sum(Type=="Guarders") )
fmts <- rep("atop(%s, n[G]==%d ~~ n[S]==%d)",nrow(sdf)) # two rows
labs2 <- do.call(sprintf,list(fmts,sdf$Year,sdf$ng, sdf$n-sdf$ng ) )
ex2 <- parse(text=labs2)
ggplot(AllData, aes(Year, AGResiduals, fill=Type)) +
geom_boxplot(outlier.size=0) +
scale_fill_manual(values=c("skyblue4", "skyblue"),
name="Male Type",
labels=c("Guarders","Sneakers")) +
labs(x=NULL, y = "Residual of Accessory Gland Mass x Total Mass") +
scale_x_discrete(limits=c("2007","2008","2010","2011","2013","2014","2015"),
labels=ex2) +
theme(plot.title = element_text(size = rel(1.4)),
axis.title = element_text(size = rel(1.2)),
axis.text.x = element_text(size = rel(1.0),angle=0,hjust=0),
axis.text.y = element_text(size = rel(1.5)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))
yields this:

Resources