use if else within ggplot chunk to change colour palette - r

I'd like to be able to change the colour palette in ggplot2 boxplots, according to another variable data_origin.
This makes my boxplots, complete with legend:
library(hrbrthemes)
library(ggplot2)
library(reshape2)
library(tidyverse)
data_origin <- "airborne"
mytitle <- "something more than this"
legend_title <- "some words"
melted <- reshape2::melt(iris)
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(palette = "Greens") +
theme(
legend.position = "bottom",
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
bp1
This however drops the legend completely and ignores the if else:
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
scale_fill_brewer(legend_title, if (data_origin == "airborne" ) {palette = "Blues"} else {palette = "Greens"}) +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
bp1

Besides what #stefan suggested, there are two ways in which you can do this (that I know of). The first is using ifelse() (I moved the relevant part to the end):
data_origin <- "airborne"
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free") +
scale_fill_brewer(legend_title, palette = ifelse(
data_origin == "airborne",
"Blues",
"Greens"
))
bp1
The other one is to build the plot up in two steps:
data_origin <- "not airborne"
bp1 <- ggplot(melted, aes(x = variable, y = value, fill = Species)) +
geom_boxplot() +
theme_ipsum() +
theme(
legend.position = "bottom",
# legend.title = legend_title,
plot.title = element_text(size = 10)) +
theme(axis.text.x = element_blank()) +
ggtitle(mytitle) +
xlab("") +
ylab("") +
facet_wrap(~variable, scale = "free")
if (data_origin == "airborne") {
bp2 <- bp1 +
scale_fill_brewer(legend_title, palette = "Blues")
} else {
bp2 <- bp1 +
scale_fill_brewer(legend_title, palette = "Greens")
}
bp2
Created on 2021-08-01 by the reprex package (v2.0.0)

Related

How to erase x label(11-28~12-02) in R ggplot

E = ggplot(km_data_person, aes(x = date, y = km,fill = "")) +
theme_minimal() +
geom_bar(stat = "identity") +
scale_fill_brewer(palette ="Paired") +
xlab("") +
ylab("") +
theme(axis.text.y = element_text(size = 18)) +
theme(legend.text = element_text(size = 20)) +
theme(axis.text.x = element_text(size = 11)) +
geom_line(data = km_data_all,
aes(date, 기관평균, color = "기관평균"),
linetype = "solid",
size = 1, group = 1) +
scale_color_manual(values = c('기관평균' = '#0066CC')) +
labs(color = '') +
theme(legend.position = "bottom") +
guides(fill = guide_legend(title = "")) +
guides(fill = "none")
The following graph is drawn from the above R code.
If I want to erase the x label how should the code change to?
E = ggplot(km_data_person,aes(x=date, y=km,fill="")) +
theme_minimal()+
geom_bar(stat="identity") +
geom_line(data=km_data_all,
aes(date,기관평균,color="기관평균"),
linetype = "solid",
size=1,
group=1)+
scale_fill_brewer(palette ="Paired")+
xlab("") +
ylab("")+
theme(axis.text.y = element_text(size = 18),
legend.text=element_text(size=20),
axis.text.x = element_blank(),
legend.position = "bottom")+
scale_color_manual(values = c('기관평균' = '#0066CC')) + labs(color = '') +
guides(fill="none")

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").

Change the font size of variable names in ggplot

I am not able to increase the font size of the names of the variables in a graphic realized with ggplot.
I tried to include these codes inside ggplot code, but unsuccessfully :
theme(text = element_text(size=20))
theme(axis.text=element_text(size=20))
theme(axis.title=element_text(size=14))
theme_grey(base_size = 20)
geom_text(size=20)
My code is :
library(ggplot2)
library(reshape2)
dataplot <- read.csv("/Documents/R.csv",header=T,sep=";")
dataPlotMelt <- melt(data = dataplot, id.vars = c("variable"),variable.name = "Method",value.name = "SMD")
varNames <- as.character(dataplot$variable)
dataPlotMelt$variable <- factor(dataPlotMelt$variable,levels = varNames)
ggplot(data=dataPlotMelt,mapping=aes(x=variable,y=SMD,group=Method, color=Method))+
ylab("Standardizedmeandifference(%)")+
xlab("") +
geom_point(aes(shape=Method),size=2) +
geom_hline(yintercept=15,color="black",size=0.1,linetype="dashed") +
geom_hline(yintercept=-15,color="black",size=0.1,linetype="dashed") +
coord_flip() +
theme(axis.text.x=element_blank()) +
scale_y_continuous(breaks=c(-65,-15,15,105)) +
theme_bw() +
theme(legend.text=element_text(size=12)) +
theme(legend.title=element_blank(),legend.key=element_blank()) +
scale_colour_manual(values=c("grey","black"))
I'd like to increase the font size of the names of the variables in the graphic and, besides, increase the text "Standardized mean difference (%)" and remove the vertical line between the yintercept and ybreak on both sides
new graphic
Thank you Richard for giving me the solution.
As you suggested I used theme after theme_bw
I managed to suppress the useless vertical lines as well with the command theme(panel.grid.minor = element_blank())
Here is the new code for ggplot :
ggplot(data = dataPlotMelt, mapping = aes(x = variable, y = SMD,group = Method,
color = Method)) +
ylab("Standardized mean difference (%)") + xlab("") +
geom_point(aes(shape = Method),size=2) +
geom_hline(yintercept = 15, color = "black", size = 0.1, linetype = "dashed") +
geom_hline(yintercept = -15, color = "black", size = 0.1, linetype = "dashed") +
coord_flip() +
theme(axis.text.x = element_blank()) +
scale_y_continuous(breaks=c(-65,-15,0,15,105)) +
theme_bw() + theme(legend.text = element_text(size=13)) +
scale_colour_manual(values= c("grey","black")) +
theme(axis.text.y = element_text(size=12)) +
theme(axis.title.x = element_text(size=13)) +
theme(panel.grid.minor = element_blank()) +
theme(legend.title = element_blank(), legend.key=element_blank())

How to add label to geom_segment at the start of the segment?

I'm sure this is simple but I can't figure it out.
I have the following chart:
library(data.table)
library(magrittr)
library(ggplot2)
cambodia <-
data.table(Period = c("Funan", "Chenla/Zhenla","Khmer Empire","Dark Ages of Cambodia"),
StartDate = c(-500,550,802,1431),
EndDate = c(550,802,1431,1863),
Color = c("lightblue","lightgreen","lightyellow","pink")) %>%
extract(order(-StartDate)) %>%
extract(, Period := factor(Period,levels = Period))
ggplot() +
geom_segment(data=cambodia, aes(x=StartDate, xend=EndDate, y=Period, yend=Period, color=Color),
linetype=1, size=2) +
scale_colour_brewer(palette = "Pastel1")+
xlab("Date")+
ylab("Ruler")+
theme_bw() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank()) +
theme(aspect.ratio = .2) +
theme(legend.position="none")
But I would like the labels to be off the axis and on the page. Either to the left or on top of the middle of the line. E.g.
Most of the examples of geom_text give me gobbledeegook. I can't seem to apply them to the factor data I have here. Do you know how to do this?
Thank you
Having the labels on the end of the segments might distort the visual mapping of segment length and location to year-range. You could put the labels in the middle of the segments instead.
library(data.table)
library(magrittr)
library(ggplot2)
library(stringr)
cambodia <-
data.table(Period = c("Funan", "Chenla/Zhenla","Khmer Empire","Dark Ages of Cambodia"),
StartDate = c(-500,550,802,1431),
EndDate = c(550,802,1431,1863),
Color = c("lightblue","lightgreen","lightyellow","pink")) %>%
extract(order(-StartDate)) %>%
extract(, Period := factor(Period,levels = Period))
ggplot(cambodia, aes(x=StartDate, xend=EndDate, y=Period, colour=Period)) +
geom_segment(aes(xend=EndDate, yend=Period), linetype=1, size=2) +
geom_label(aes(label=str_wrap(Period,12), x=(StartDate + EndDate)/2), size=3) +
scale_colour_brewer(palette = "Set1") +
xlab("Date")+ ylab("Ruler")+
theme_bw() +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
aspect.ratio = .2,
legend.position="none",
axis.text.y=element_blank(),
axis.ticks.y=element_blank())
Or what about going minimal:
ggplot(cambodia, aes(x=StartDate, y=1)) +
geom_rect(aes(xmin=StartDate, xmax=EndDate, ymin=0.97, ymax=1.03, fill=Period),
show.legend=FALSE, colour="white", size=0.5) +
geom_label(aes(label=str_wrap(Period,12), x=(StartDate + EndDate)/2), size=3.5) +
geom_text(aes(label=StartDate, y=0.96), size=3.5) +
geom_text(aes(label=ifelse(EndDate==max(EndDate), EndDate,""), x=EndDate, y=0.96), size=3.5) +
scale_colour_brewer(palette = "Set1") +
scale_y_continuous(limits=c(0.95,1.05)) +
theme_void()
ggplot() +
geom_segment(data=cambodia, aes(x=StartDate, xend=EndDate, y=Period, yend=Period, color=Color),
linetype=1, size=2) +
geom_label(data=cambodia, aes(x=StartDate, y=Period, label = Period),
nudge_x = c(-300, -200, -200, -100)) +
scale_colour_brewer(palette = "Pastel1")+
xlab("Date")+
ylab("")+
theme_bw() +
theme(legend.position="none") +
theme(aspect.ratio = .2) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_blank(),
axis.line.y = element_blank(), axis.text.y = element_blank(),
axis.ticks.y = element_blank())
You need to use element_blank() to remove the y axis elements and then use nudge_x argument in geom_label to offset the labels appropriately.

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