how to plot two stacked bar graph in r - r

I had two stacked bar graphs, one for input another for output.
however i want to plot these two graphs in one space.
I attached the sample.
Please help me!! thank you!!
gr_out <- read.csv("graph_out.csv",header=TRUE, sep=",")
library(ggplot2)
library(reshape2)
gr_out.metlt<-melt(gr_out)
head(gr_out.metlt)
gr_out.metlt$DMU.Name <- factor(gr_out.metlt$DMU.Name, levels = gr_out$DMU.Name)
q <- ggplot(gr_out.metlt, aes(x = DMU.Name, y = value),add=TRUE)
q + geom_bar(aes(fill = variable), stat = "identity") + theme_bw() +
theme(axis.text.x = element_text(angle=60, hjust=1),panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
ylab("Cummulative ratio") + xlab("Station") + scale_fill_brewer(palette = "Paired")
##graph
gr_in <- read.csv("graph_in.csv",header=TRUE, sep=",")
library(ggplot2)
library(reshape2)
gr_in.metlt<-melt(gr_in)
head(gr_in.metlt)
gr_in.metlt$DMU.Name <- factor(gr_in.metlt$DMU.Name, levels = gr_in$DMU.Name)
p <- ggplot(gr_in.metlt, aes(x = DMU.Name, y = value))
p + geom_bar(aes(fill = variable), stat = "identity") + theme_bw() +
theme(axis.text.x = element_text(angle=60, hjust=1),panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
ylim(c(0.0, 8.0)) + ylab("Cummulative ratio") + xlab("Station")+ scale_fill_brewer(palette = "Paired")
This is what I want to achieve

Related

How to make a pie chart with factor

I want to make pie chart with factor column using ggplot, I want to show percentage, frequency, and Trial phase for each:
This is my code:
library(ggplot2)
library(ggrepel)
library(dplyr)
library(cowplot)
#Retrieve data
figvac <- read.csv(url("https://raw.githubusercontent.com/learnseq/learning/main/vaccinedev.txt"),sep = '\t',header = TRUE)
library(repr, warn.conflicts = FALSE)
options(repr.plot.width=17, repr.plot.height=10)
ggplot(figvac, aes(x="", fill=factor(figvac[, 2] ))) + geom_bar(width = 1) + coord_polar("y", start=0)
I tried
geom_text(aes(label = paste(round(factor(figvac[, 2] / sum(factor(figvac[, 2]) * 100, 1), "%"))),
position = position_stack(vjust = 0.5)) +
theme_classic() +
theme(plot.title = element_text(hjust=0.5),
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank()) +
labs(fill = "Category",
x = NULL,
y = NULL,
title = "Pie Chart of Vaccines") +
coord_polar("y")
But it did not work.
You want fill=factor(Mechanism)
This should do the trick:
library(ggplot2)
figvac <- read.csv(url("https://raw.githubusercontent.com/learnseq/learning/main/vaccinedev.txt"),sep = '\t',header = TRUE)
ggplot(figvac, aes(x=Mechanism, fill=Mechanism)) +
geom_bar(width = 1) +
coord_polar()

Reordering Plot and Changing Axis Size (R ggplot)

I'm trying to change in both of my plots, the order and the x axis size for both. These are not being able to be changed accordingly
DF Creation
contig_count_average <- data.frame(Genome_Type = c("MBT", "Anglucyclines", "Whole Genome"),
Contig_Count_Average = c("2.91","83.7","608.3"))
Plot
p2 <- ggplot(contig_count_average, mapping = aes(x = reorder(Genome_Type, Contig_Count_Average), Contig_Count_Average, fill = Genome_Type)) +
xlab("Genome") +
ylab("Contig No.") +
ggtitle("Contig Count per Genome Distribution") +
geom_bar(stat = "identity") +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1)) +
guides(fill=guide_legend(title="Genome Type")) +
coord_flip() +
theme_bw() +
scale_y_continuous(limits = c(0,2835), expand = c(0, 0)) +
scale_x_discrete(labels = abbreviate)
p
I get the following warning:
1: In Ops.factor(Contig_Count_Average) : ‘-’ not meaningful for factors
The issue is because Contig_Count_Average is treated as factors in contig_count_average.
We can change it to numeric by doing either :
contig_count_average <- type.convert(contig_count_average, as.is = TRUE
Or
contig_count_average$Contig_Count_Average <- as.numeric(as.character(contig_count_average$Contig_Count_Average))
and then use the ggplot code.
p2 <- ggplot(contig_count_average, mapping = aes(x = reorder(Genome_Type,
Contig_Count_Average), Contig_Count_Average, fill = Genome_Type)) +
xlab("Genome") +
ylab("Contig No.") +
ggtitle("Contig Count per Genome Distribution") +
geom_bar(stat = "identity") +
theme(text = element_text(size=20),
axis.text.x = element_text(angle=90, hjust=1)) +
guides(fill=guide_legend(title="Genome Type")) +
coord_flip() +
theme_bw() +
scale_y_continuous(limits = c(0,2835), expand = c(0, 0)) +
scale_x_discrete(labels = abbreviate)
p2
Also note that you can use geom_col instead of geom_bar(stat = "identity").

How to add superscripts to facet labels

I am trying to plot three variables and want the units in the axes labels but can't find a way to label them properly in facets with the superscripts.
I've tried as_labeller, label_bquote, expression/paste and changing the original data.
p <- ggplot(data = LST, aes(x = Date, y = Measurements)) +
geom_point((aes(color = parameter)))
p + facet_grid(parameter ~ ., scales = "free_y",
switch="y",labeller=as_labeller(DO~(mg~L^{-1}), Temperature~(°C), Light~
(µmol~m^{-2}~s^{-1}))) +
theme_bw()+ theme(strip.background = element_blank(),
legend.title = element_blank(), strip.placement = "outside",
panel.grid.minor = element_blank()) +
scale_x_datetime()+ ylab(NULL) +ggtitle("Spring 2018") +
scale_colour_manual(values=c('royalblue1', 'springgreen4', 'darkblue')) +
theme(legend.position="none")+
theme(strip.text=element_text(size=10))
Everything I try either labels all facets the same or doesn't place the superscripts. I'm pretty new at ggplot2 so am unsure if what I'm trying will help.
You want labeller = label_parsed. Here's a simple example
mt = mtcars
mt$facets = factor(mt$cyl, labels = c(
"DO~(mg~L^{-1})",
"Temperature~('°C')",
"Light~(µmol~m^{-2}~s^{-1})"))
ggplot(mt, aes(mpg,cyl)) +
geom_point() +
facet_grid(~facets, labeller = label_parsed)

Split parts of a stacked barplot into individual series

I want to create in R 3.2.2 a barplot with stacked bars but with each part of each bar splitted into an individual series.
Example data frame:
num_var_x = 14
num_var_y = 17
x = runif(num_var_x, 0.0, 1.0)
norm = x/sum(x)
data = data.frame(replicate(num_var_y,sample(norm)))
EDIT:
Thanks to Floo0 I have come up with this continuation of the code:
## preparing dataset for ggplot
require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")
data_molten_sort = data_molten[with(data_molten,order(no)),]
## removing elements from variable 'no' whose max. value is e.g. < 0.025
sequence = seq(from=1, to=(num_var_y*num_var_x-num_var_x)+1, by=num_var_x)
for(i in 1:length(sequence))
{
if(isTRUE((max(data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))])) < 0.025))
{
data_molten_sort$value[(sequence[i]):((num_var_x+sequence[i])-(1))] = NA
}
}
View(data_molten)
## preparing posterior exporting
#install.packages("Cairo"); "cairo" type in png() has a better quality
library("Cairo")
#preparing exporting
png(file="ggplot.png",type="cairo", width = 4, height = 5, units = 'in',pointsize=8,res=600)
## plotting
ggplot(data_molten[!is.na(data_molten$value),], aes(x = variable, y = value, fill = factor(no))) +
geom_bar(stat = "identity") +
scale_fill_hue(l=40) + facet_grid(no~., as.table=FALSE, scale="free_y", space = "free_y") + theme_minimal() +
geom_vline(xintercept=max(as.numeric(data_molten$variable)) + 0.586, size=0.3) +
theme(legend.position="none",
axis.text.x = element_text(angle = 90, colour="black", vjust = 0.4, hjust=1, size=8),
axis.title.x = element_blank(), axis.title.y = element_blank(),
axis.line.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
strip.text.y=element_text(size = 8, colour="black", family="", angle=00,hjust = 0.1),
panel.grid=element_blank(),
axis.line=element_line(size = 0.3, colour = "black", linetype = "solid"),
axis.ticks.x=element_line(size = 0.3, colour = "black", linetype = "solid"),
panel.background=element_blank(), panel.margin = unit(0, "lines"))
## exporting barplot "ggplot.png" to directory
dev.off()
which produces the desired barplot:
http://i.imgur.com/C6h5fPg.png?1
You can use ggplot2 to do that as follows:
require(ggplot2)
require(reshape2)
data$no <- seq_len(nrow(data))
data_molten <- melt(data, id.vars = "no")
If you want the rows to have different hights, have a look at: Different y-Axis Labels facet_grid and sizes
I am not 100% sure in which direction you want the plot to be turned:
Version 1
ggplot(data_molten, aes(x = no, y = value, fill = variable)) + geom_bar(stat = "identity") +
facet_grid(variable~.) + theme(legend.position="none")
Version 2
Thx bergant fot the comment
ggplot(data_molten, aes(x = variable, y = value, fill = factor(no))) + geom_bar(stat = "identity") +
facet_grid(no~.) + theme(legend.position="none")
Original
ggplot(data_molten, aes(x = no, y = value, fill = variable)) + geom_bar(stat = "identity")

Change colour of bar ggplot2

I am making a bar graph trying to change the colour of my bars using this code, but it does not seem to be working. What is the problem?
ggplot(hd.m, aes(provinces, value)) + geom_bar(aes(fill="#0072B2"), position = "dodge", stat="identity") + scale_fill_discrete(guide=FALSE) + xlab("Provinces and Territories") + ylab("Percentage(%)") + ggtitle("Heart Disease Prevelance across Canada in 2008-2009") + theme_bw() + theme(panel.border = element_blank()) + theme(
plot.title = element_text(size=20),
axis.title.x = element_text(size=14), axis.title.y = element_text(size=14)) + geom_hline(yintercept=4.7)
Take the fill out of the aes.
library(ggplot2)
df <- data.frame(x = c("AB","BC","MB"), y = c(3.5,3.9,4.6))
# You have:
ggplot(df, aes(x,y)) + geom_bar(aes(fill="blue"), stat="identity")
# Try:
ggplot(df, aes(x,y)) + geom_bar(fill="blue", stat="identity")

Resources