Export from ggplot2 dark theme with no white border? - r

I want my plots to have dark background to match a slide theme that I am using. I have everything the way I want it, but I cannot figure out how to remove the white border from the overall image. I am looking for something like theme(plot.border = element_line(color = "#1e1e1e")) but there does not seem to be a plot.border attribute.
No matter what I do to my export size, it always includes it. I never even knew there was a border in the past because I was always using white on white, but now it is revealed!
I've tried a bunch of stuff and cannot get rid of that stupid line, and I really don't want to have to crop my images to remove, or take manual screenshots from RStudio :)
Here's the code, and see below for the image it's creating...
p<- ggplot(barchart.data, aes(x=x_labs, y=ests, fill=l_labs)) +
geom_bar(stat="identity", color=fill_colors, position=position_dodge(), fill=fill_colors) +
geom_text(aes(y=ests+perrs+0.02, label=sprintf("%1.1f%%", 100*ests)), vjust=0.5, hjust=0, size=bar.font, color="white") +
geom_errorbar(aes(ymin=ests-nerrs, ymax=ests+perrs), width=.2, position=position_dodge(.9), color="white", size=0.25) +
labs(title=chtit, x=xaxis, y = yaxis) +
theme_classic() +
scale_y_continuous(limits = c(0,1.1), breaks=c(0, 0.2, 0.4, 0.6, 0.8, 1)) +
theme(legend.position="none", legend.text = element_text(color = "white")) +
theme(title = element_text(colour = "white")) +
theme(axis.text = element_text(size=12, color = "white"), axis.line = element_line(color = "white")) +
theme(axis.title = element_text(size=12, color = "white")) +
coord_flip() +
theme(panel.grid.major.x = element_line(colour = "white",size=0.25))+
theme(aspect.ratio = 1) +
theme(panel.background = element_rect(fill = "#1e1e1e")) +
theme(plot.background = element_rect(fill = "#1e1e1e")) +
guides(fill = guide_legend(reverse = TRUE))
return(p)

Related

Change color in a stack bar plot with more than 11 colours

I'm a beginner using R and I'm creating a ggplot-geom_bar (stack) to demonstrate diferences in percentage of compounds. However I have more than 11 colours and I cannot change the fill colours
I'm using the following code:
vermelha_bio_stack <- ggplot() +
geom_bar(data=vermelha_pom,
aes(y=values, x=month,fill= factor(compunds)),
stat="identity") +
xlab("") +
ylab("Percentages") +
scale_fill_discrete(name = "Compounds") +
scale_y_continuous(limits = c(0,101), expand=c(0,0)) +
theme_classic() +
theme(
text=element_text(family = "sans"),
axis.ticks.x = element_blank(),
axis.line.x.bottom = element_line (color = "black"),
axis.line.y.left = element_line(color = "black"),
panel.background = element_rect(fill = "white")) +
ggtitle("Lagoa Vermelha") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))+
coord_flip()
and I got the following plot
but I want colours like the following image:

R ggplot geom_text wipes out background--bug?

I found an issue with ggplot2::geom_text() when I attempt to highlight my data with labels. My MWE illustrates the situation. After I define the plot I add the theme() from phase#1 which colors the panel and plot backgrounds. The red/green is for emphasis. When the labels are added in phase#2, the plot.background goes to white and the panel background to the default grey. Is this something I'm doing, is this an undocumented feature of ggplot2, or is this a bug?
require(ggplot2)
SESnow <- data.frame(Year=c(1978,1988,1995,2000,2013,2017),
Snow=c(355.9,322.1,329.1,303.6,318.5,304.0))
p <- ggplot(SESnow, aes(x=Year, y=Snow, fill=Snow)) +
geom_col(width=1) +
scale_fill_gradient(low="blue", high="red", limits=c(0,400)) +
theme(axis.title.y=element_text(angle=0)) +
ggtitle("Yearly Total Snowfall (inch)") +
labs(subtitle = "Copper City 2019",
caption="Source: Keweenaw County",
x="Snow Season") +
theme(legend.position="none")
#phase#1
p + theme( panel.background = element_rect(fill = "green",
colour = "black",
size = 0.5, linetype = "solid"),
plot.background = element_rect(fill = "blue",
colour = "black",
size = 0.5, linetype = "solid"),
axis.text.x = element_text(colour="grey20",size=11, vjust=1,
margin=margin(t=0,b=0),face="bold"),
axis.text.y = element_text(colour="grey20",size=11, hjust=1,
margin=margin(t=10,b=10),face="bold") )
#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ), y = SESnow$Snow + 20.0,
label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
color="black")
Also note that if you run phase#1 after phase#2 the labels disappear, so this feature is consistent. How do I get a plot with labels and colored background?
The answer is simple. You are generating two plots instead of one. You need to store the plot in p if you want to use the same plot and modify it later.
#phase#1
p <- p + theme( panel.background = element_rect(fill = "green",
colour = "black",
size = 0.5, linetype = "solid"),
plot.background = element_rect(fill = "blue",
colour = "black",
size = 0.5, linetype = "solid"),
axis.text.x = element_text(colour="grey20",size=11, vjust=1,
margin=margin(t=0,b=0),face="bold"),
axis.text.y = element_text(colour="grey20",size=11, hjust=1,
margin=margin(t=10,b=10),face="bold") )
#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ), y = SESnow$Snow + 20.0,
label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
color="black")
Assign the value to p before you use it again. This will solve the issue.
Edit: I am attaching the graph. I guess this is what you wanted.

Change line type of border

I would like to change the line type of the panel border from solid line to dashed line in my graph. I tried to use panel.border and panel_border in theme, but R keep telling me it cannot find these two functions in theme.
I think this will be very difficult to do with theme options. Even when the panel spacing is 0, I'm pretty sure it's using element_rect to draw the panel borders. Getting the plot you want with theme modifications would require modifying 1 or 2 lines of each panel border with awareness of whether the facet is a left, right, or central facet.
To get around this we can use hline and vline instead. Hacky, but it works:
hline_df = expand.grid(visit = unique(df$visit), yint = c(-Inf, Inf))
vline_df = expand.grid(visit = unique(df$visit), xint = c(-Inf, Inf)) %>%
mutate(no_dash = !(
(xint == Inf & visit == tail(levels(visit), 1)) |
(xint == -Inf & visit == head(levels(visit), 1))
))
ggplot(df, aes(x=avisit, y=mean, group=Type, color=Type, shape=Type)) +
scale_y_continuous(breaks=seq(0,18,2), limits=c(0, 18)) +
geom_point(position=pd, cex=2) +
xlab("") +
ylab("Mean") +
scale_colour_manual(values=c("blue", "red")) +
scale_shape_manual(values=c("triangle", "circle")) +
coord_cartesian(ylim = c(0, 18)) +
facet_grid(.~factor(visit), scales = "free_x", space ="free_x",switch = "both") +
geom_hline(data = hline_df, aes(yintercept = yint)) +
geom_vline(data = vline_df, aes(xintercept = xint, linetype = no_dash), show.legend = FALSE) +
theme_bw() +
theme(axis.text.y = element_text(margin = margin(r = 0)),
panel.spacing = unit(0, "mm"),
strip.background = element_blank(),
legend.title=element_blank(),
strip.placement = "outside",
legend.background = element_rect(color="black", fill="white", size=0.5, linetype="solid"),
legend.direction = "horizontal",
panel.grid.minor = element_line(colour="white", linetype="dashed"),
panel.grid.major = element_line(colour = "white",linetype="dashed"),
panel.border = element_blank())
element_rect takes a linetype argument. It might draw the axis line on top of the border or vice versa, so you can modify axis.line too. This theme should give you what you want and will be a little more elegant:
ggplot() + theme(axis.line = element_line(linetype = 3), panel.border = element_rect(linetype =3)

Saving a dark-themed plot using ggsave() creates white bordering panels

I need my charts to have a dark gray theme to match a presentation style. I also need them to be fixed height, but the widths may vary depending on the length of the labels on the y-axis. When I try to export or save, there are always white side bars in the .jpg or .png file.
Here's some sample code that I use to create the chart (there are some extra theming controls in here that are superfluous to the simplified example, but the resulting chart is basically what I am generating):
library(ggplot2)
bar.font <- 8
title <- "Example"
l_labs <- c("")
x_labs <- c("A","B","C")
ests <- c(.5,.3,.2)
nerrs <- c(.05, .05, .05)
perrs <- nerrs
barchart.data <- data.frame(l_labs, x_labs, ests, nerrs, perrs)
p <- ggplot(barchart.data, aes(x=x_labs, y=ests*100)) +
geom_bar(stat="identity", color="#808080", position=position_dodge(), width=0.85, fill="#808080") +
geom_text(aes(y=ests*100+perrs*100+1.5, label=sprintf("%1.1f%%", 100*ests)), vjust=0.5, hjust=0, size=bar.font, color="white") +
geom_errorbar(aes(ymin=ests*100-nerrs*100, ymax=ests*100+perrs*100), width=.2, position=position_dodge(.9), color="white", size=0.25) +
labs(title=title, x="", y = "") + theme_classic() +
scale_y_continuous(expand = c(0,0),limits = c(0,115), breaks=c(0, 20, 40, 60, 80, 100)) +
theme(legend.position="none", legend.text = element_text(color = "white")) +
theme(title = element_text(size=18, colour = "white")) +
theme(axis.text = element_text(size=20, color = "white"), axis.line = element_line(color = "white")) +
theme(axis.text.x = element_text(margin=margin(9,0,0,0)),axis.text.y = element_text(margin=margin(0,9,0,0))) +
theme(axis.title = element_text(size=20, color = "white")) +
theme(axis.title.x = element_text(margin = margin(10,0,0,0))) +
theme(axis.ticks = element_line(colour = 'white', size = .5)) +
coord_flip() +
theme(aspect.ratio = 1) +
theme(panel.background = element_rect(fill = "#1e1e1e")) +
theme(legend.justification=c(1,0), legend.position=c(1,0)) +
theme(plot.background = element_rect(fill = "#1e1e1e", color = "#1e1e1e")) +
theme(panel.grid.major.x = element_line(colour = "white",size=0.1, linetype = "dotted"))
ggsave("test.jpg", height=10, units="in")
And here is what the exported .jpg looks like. I cannot specify an exact width because I do not know what it will be for each chart as the widths vary. Thanks for any guidance.
You can set the background color to whatever value you like:
ggsave("test.jpg", height=10, units="in", bg = "#1e1e1e")
This takes care of the white bars.
It may be a bit confusing that the bg option is not mentioned in the ggsave() documentation. That's because it's part of the graphics device, here jpeg(). It is mentioned in the jpeg() documentation.
The reason why there are white bars in the first place is discussed in depth in this post.

ggplot embedded fonts in pdf

I have been using the following guide to export plots made with ggplotto pdf: plot fonts guide
It raises the issue at the bottom of the post of some fonts not appearing as they should, which happens in my example below. The text in font Bauhaus 93 appears correctly whilst the text in Calibri is displayed incorrectly.
Has anyone found a way to resolve this issue?
library(ggplot2)
library(plyr)
library(grid)
library(gridExtra)
library(extrafont)
data1<-as.data.frame(1:5)
data1[,2]<-as.data.frame(c(1,3,5,7,9))
data1[,3]<-as.data.frame(c(2,4,6,8,10))
colnames(data1)<-c("x","y1","y2")
ggplot(data1, aes(x=x)) +
geom_line(aes(y = y1, colour = "Taux selon DEF"), size=0.61, colour="black") +
geom_line(aes(y = y2, colour = "Taux selon EC"), size=0.61, colour="black", linetype="dashed") +
xlab("X axis lab") + ylab("Y axis lab)") +
annotate("text", x=1, y=4, label="Some text here", size=2, family="Bauhaus 93") +
annotate("text", x=4, y=1, label="More text here", size=2, family="Calibri") +
theme_bw() + theme(legend.title = element_blank(),
legend.key = element_rect(fill=NA),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=0.25),
axis.ticks = element_line(size=0.25),
panel.grid.major = element_line(colour = "grey80", size=0.25),
panel.grid.minor = element_line(colour = "grey80", size=0.25),
axis.text.x = element_text(size=5.5 , lineheight=0.9, hjust=0.5, family="Bauhaus 93"),
axis.text.y = element_text(size=5.5 , lineheight=0.9, vjust=0.5, family="Calibri"),
axis.title.y = element_text(size=6.1, angle=0, vjust=0.975, face="bold", family="Calibri"),
axis.title.x = element_text(size=6.1, angle=0, vjust=-0.20, face="bold", family="Calibri")) +
scale_x_continuous(expand = c(0, 0), limits=c(0,5)) +
scale_y_continuous(expand = c(0, 0), limits=c(0,10)) +
ggtitle("Title") +
ggsave("Test.pdf", width=7, height=5)
Sys.setenv(R_GSCMD = "C:/Program Files (x86)/PDF24/gs/bin/gswin32.exe")
embed_fonts("Test.pdf")
Try adding device=cairo_pdf to the ggsave() call. This appears to solve the problem for me. This way, it's no longer necessary to use embed_fonts().
See mgaudet's comment here: https://github.com/wch/extrafont/issues/8

Resources