ggplot classic theme missing axes [duplicate] - r

I am trying to draw this following graph using ggplot2 package, but somehow the axis won't show up. the ticks are there, just not the axis line. I have used the theme(axis.line=element_line()) function, but it wouldn't work.
Here is my code:
library(ggplot2)
ggplot(data = soepl_randsub, aes(x = year, y =satisf_org, group = id)) +
geom_point() + geom_line() +ylab("Current Life Satisfaction") +theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() ) +
theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = "2"))
I am not sure what went wrong. Here is the chart.

The bug was fixed in ggplot2 v2.2.0 There is no longer a need to specify axis lines separately.
I think this is a bug in ggplot2 v2.1.0. (See this bug report and this one.) A workaround is to set the x-axis and y-axis lines separately.
library(ggplot2)
ggplot(data = mpg, aes(x = hwy, y = displ)) +
geom_point() +
theme_bw() +
theme(plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank() )+
theme(panel.border= element_blank())+
theme(axis.line.x = element_line(color="black", size = 2),
axis.line.y = element_line(color="black", size = 2))

You don't need to specify axis-size for X and Y separately. When you are specifying size="2", R is considering value 2 as non-numeric argument. Hence, axis-line parameter is defaulted to 0 size. Use this line of code:
ggplot(data = mpg, aes(x = hwy, y = displ)) + geom_point() +xlab("Date")+ylab("Value of Home")+theme_bw() +theme(plot.background = element_blank(),panel.grid.major = element_blank(),panel.grid.minor = element_blank()) + theme(panel.border= element_blank()) +
theme(axis.line = element_line(color="black", size = 2))
axis_line inherits from line in R, hence specifying size is mandatory for non-default values.

Related

Adjust the length of facet_wrap so that each facet reflect number of samples?

I have a plot that looks like below. However as you can see facet 4 only has 1 sample but the vertical size is equal to facet 6 which has 4 samples; this makes the plot look really weird since it becomes really thick. I can't use face_grid (facet_grid( cyl~. , scales = "free", space="free" )) at the moment because because then the labels goes to the side but what I really want is to put the labels on top like with facet_wrap as illustrated below. Is there anyway around this? thanks.
temp = head ( mtcars )
temp$car = row.names ( temp )
ggplot( temp , aes(x=car , y=hp, fill=vs )) +
geom_bar(stat = 'identity', position = 'stack') +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
coord_flip() +
scale_y_continuous(expand = expansion(mult = c(0, .1))) +
facet_wrap( ~cyl , ncol=1, scales = "free" )
Not sure if you want this. If so, you can use facet_col from the package ggforce, which allows you to have facet in a single column and also drop the facet ratio (space argument).
library(tidyverse)
library(ggforce)
temp = head (mtcars)
temp$car = row.names(temp)
ggplot(temp, aes(x = car , y = hp, fill = vs)) +
geom_bar(stat = 'identity', position = 'stack') +
theme_bw() +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
coord_flip() +
scale_y_continuous(expand = expansion(mult = c(0, .1))) +
ggforce::facet_col(cyl ~ ., scales = "free", space = "free")

move legend title in ggplot2

I have been trying to shift my legend title across to be centered over the legend contents using the guide function. I've been trying to use the following code:
guides(colour=guide_legend(title.hjust = 20))
I thought of trying to make a reproducable example, but I think the reason it's not working has something to do with the above line not matching the rest of my code specifically. So here is the rest of the code I'm using in my plot:
NH4.cum <- ggplot(data=NH4_by_Date, aes(x=date, y=avg.NH4, group = CO2, colour=CO2)) +
geom_line(aes(linetype=CO2), size=1) + #line options
geom_point(size=3) + #point symbol sizes
#scale_shape_manual(values = c(1, 16)) + #manually choose symbols
theme_bw()+
theme(axis.text.x=element_text(colour="white"), #change x axis labels to white.
axis.title=element_text(size=12),
axis.title.x = element_text(color="white"), #Change x axis label colour to white
panel.border = element_blank(), #remove box boarder
axis.line.x = element_line(color="black", size = 0.5), #add x axis line
axis.line.y = element_line(color="black", size = 0.5), #add y axis line
legend.key = element_blank(), #remove grey box from around legend
legend.position = c(0.9, 0.6))+ #change legend position
geom_vline(xintercept=c(1.4,7.5), linetype="dotted", color="black")+ #put in dotted lines for season boundaries
scale_color_manual(values = c("#FF6600", "green4", "#0099FF"),
name=expression(CO[2]~concentration~(ppm))) + #manually define line colour
scale_linetype_manual(guide="none", values=c("solid", "solid", "solid")) + #manually define line types
scale_shape_manual(values = c(16, 16, 16)) + #manually choose symbols
guides(colour=guide_legend(title.hjust = 20))+
scale_y_continuous(expand = c(0, 0), limits = c(0,2200), breaks=seq(0,2200,200))+ #change x axis to intercept y axis at 0
xlab("Date")+
ylab(expression(Membrane~available~NH[4]^{" +"}~-N~(~mu~g~resin^{-1}~14~day^{-1})))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_errorbar(aes(ymin = avg.NH4 - se.NH4, #set y error bars
ymax = avg.NH4 + se.NH4),
width=0.1)
I have tried doing the following instead with no luck:
guides(fill=guide_legend(title.hjust=20)
I have also adjusted the hjust value from values between -2 to 20 just to see if that made a difference but it didn't.
I'll try to attach a picture of the graph so far so you can see what I'm talking about.
I've looked through all the questions I can on stack overflow and to the best of my knowledge this is not a duplicate as it's specific to a coding error of my own somewhere.
Thank-you in advance!!
The obvious approach e.g.
theme(legend.title = element_text(hjust = .5))
didn't work for me. I wonder if it is related to this open issue in ggplot2. In any case, one manual approach would be to remove the legend title, and position a new one manually:
ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point() +
stat_smooth(se = FALSE) +
theme_bw() +
theme(legend.position = c(.85, .6),
legend.title = element_blank(),
legend.background = element_rect(fill = alpha("white", 0)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
annotate("text", x = 5, y = 27, size = 3,
label = "CO[2]~concentration~(ppm)", parse = TRUE)
Output:

Creating a composite plot using ggplot in R

I am pretty new to R and am trying to create a composite plot using ggplot. I have searched how to do this and have seen I can use the facet function, however, it seems that this is for plotting data which can be split by type e.g. male/female. I have a data frame and I want to plot recovery against concentration, and recovery against equilibrium time on separate plots but as a composite plot. For this I have the following code:
p1 <- ggplot(dat2, aes(x = EqmTime, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p1 + geom_point(size = 4) + geom_errorbar(limits, width=4) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Equilibrium Time (hrs)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
p2 <- ggplot(dat2, aes(x = StockConc, y = Recovery))
limits <- aes(ymax = Recovery + RecoveryError, ymin=Recovery - RecoveryError)
p2 + geom_point(size = 4) + geom_errorbar(limits, width=0.1) + geom_smooth(method = "lm", se = FALSE, colour="gray", size=1.5, linetype="dashed") +
labs(x='Concentration (g L-1)', y='Nitrate Recovery (%)') + theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Additionally, I also have a problem that I cannot get the '-1' in the x axis label of plot 2 as a superscript, and am having trouble setting axis limits. When I set, for example, xlim=20-180, the axis doesn't start and finish at these, but makes these the major tick marks.
I would greatly appreciate any help with this! I know some of these issues have been addressed in other posts but I cannot seem to use this advise to sort the issue here.
From your question, I understand that you want to plot both the ggplots in single plot window. You can do this using gridextra package as:
library(gridExtra)
grid.arrange(p1, p2, nrow=2)

ggplot2 & facet_wrap - eliminate vertical distance between facets

I'm working with some data that I want to display as a nxn grid of plots. Edit: To be more clear, there's 21 categories in my data. I want to facet by category, and have those 21 plots in a 5 x 5 square grid (where the orphan is by itself on the fifth row). Thus facet_wrap instead of facet_grid.
I've got the following code written up for doing it (using the good old iris data set for my reproducible example):
library(ggplot2)
library(grid)
cust_theme <- theme_bw() + theme(legend.position="none",
axis.title = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank(), strip.text = element_blank(),
strip.background = element_blank(), panel.margin = unit(0, "lines"),
panel.border = element_rect(size = 0.25, color = "black"),
panel.grid = element_blank())
iris.plot <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() + cust_theme + facet_wrap( ~ Species, ncol = 2) +
labs(title = "Irises by species")
This gives me ALMOST what I want, but not quite:
I've still got a tiny strip of space between the top row of plots and the bottom row. I'd like to get rid of that entirely, but panel.margin is obviously not doing it. Is there a way to do this?
This might be a little late, but panel.marginis now deprecated. Inside theme use panel.spacing. To eliminate the spacing between the facets then load the grid package and use panel.spacing = unit(0, "lines")
Change the panel.margin argument to panel.margin = unit(c(-0.5,0-0.5,0), "lines"). For some reason the top and bottom margins need to be negative to line up perfectly. Here is the result:
You can also edit the grobs directly:
library(ggplot2)
library(grid)
g <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
facet_wrap( ~ Species, ncol = 2) +
labs(title = "Irises by species") +
theme_bw() +
theme(panel.margin = unit(0, "lines")) +
theme(plot.margin = unit(c(0,0,0,0), "lines")) +
theme(strip.background = element_blank()) +
theme(plot.background = element_blank()) +
theme(strip.text = element_blank()) +
theme(axis.ticks.margin = unit(0, "lines"))
g <- ggplotGrob(p)
g$heights[[7]] = unit(0, "lines")
grid.newpage()
grid.draw(g)

Remove grid, background color, and top and right borders from ggplot2

I would like to reproduce the plot immediately below by using ggplot2. I can come close, but cannot remove the top and right borders. Below I present several attempts using ggplot2, including several suggestions found on or via Stackoverflow. Unfortunately I have not been able to get those suggestions to work.
I am hoping someone may be able to correct one or more of the code snippets below.
Thank you for any suggestions.
# desired plot
a <- seq(1,20)
b <- a^0.25
plot(a,b, bty = "l")
library(ggplot2)
df <- as.data.frame(cbind(a,b))
# 1. ggplot2 default
ggplot(df, aes(x = a, y = b)) + geom_point()
# 2. removes background color
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black'))
# 3. also removes gridlines
none <- theme_blank()
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none)
# 4. does not remove top and right border
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(panel.border = none)
# 5. does not remove top and right border
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(axis.line = theme_segment())
# 6. removes x and y axis in addition to top and right border
# http://stackoverflow.com/questions/5458409/remove-top-and-right-border-from-ggplot2
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(panel.background=theme_rect(colour=NA))
# 7. returns error when attempting to remove top and right border
# https://groups.google.com/group/ggplot2/browse_thread/thread/f998d113638bf251
#
# Error in el(...) : could not find function "polylineGrob"
#
theme_L_border <- function(colour = "black", size = 1, linetype = 1) {
structure(
function(x = 0, y = 0, width = 1, height = 1, ...) {
polylineGrob(
x=c(x+width, x, x), y=c(y,y,y+height), ..., default.units = "npc",
gp=gpar(lwd=size, col=colour, lty=linetype),
)
},
class = "theme",
type = "box",
call = match.call()
)
}
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts( panel.border = theme_L_border())
EDIT Ignore this answer. There are now better answers. See the comments. Use + theme_classic()
EDIT
This is a better version. The bug mentioned below in the original post remains (I think). But the axis line is drawn under the panel. Therefore, remove both the panel.border and panel.background to see the axis lines.
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- data.frame(a,b)
ggplot(df, aes(x = a, y = b)) + geom_point() +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Original post
This gets close. There was a bug with axis.line not working on the y-axis (see here), that appears not to be fixed yet. Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline.
library(ggplot2)
library(grid)
a <- seq(1,20)
b <- a^0.25
df <- data.frame(a,b)
p = ggplot(df, aes(x = a, y = b)) + geom_point() +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
p
The extreme points are clipped, but the clipping can be undone using code by baptiste.
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or use limits to move the boundaries of the panel.
ggplot(df, aes(x = a, y = b)) + geom_point() +
xlim(0,22) + ylim(.95, 2.1) +
scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.
Here's updated code reflecting current ggplot syntax:
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
#base ggplot object
p <- ggplot(df, aes(x = a, y = b))
p +
#plots the points
geom_point() +
#theme with white background
theme_bw() +
#eliminates background, gridlines, and chart border
theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank()
) +
#draws x and y axis line
theme(axis.line = element_line(color = 'black'))
generates:
An alternative to theme_classic() is the theme that comes with the cowplot package, theme_cowplot() (loaded automatically with the package). It looks similar to theme_classic(), with a few subtle differences. Most importantly, the default label sizes are larger, so the resulting figures can be used in publications without further modifications needed (in particular if you save them with save_plot() instead of ggsave()). Also, the background is transparent, not white, which may be useful if you want to edit the figure in illustrator. Finally, faceted plots look better, in my opinion.
Example:
library(cowplot)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p <- ggplot(df, aes(x = a, y = b)) + geom_point()
save_plot('plot.png', p) # alternative to ggsave, with default settings that work well with the theme
This is what the file plot.png produced by this code looks like:
Disclaimer: I'm the package author.
I followed Andrew's answer, but I also had to follow https://stackoverflow.com/a/35833548 and set the x and y axes separately due to a bug in my version of ggplot (v2.1.0).
Instead of
theme(axis.line = element_line(color = 'black'))
I used
theme(axis.line.x = element_line(color="black", size = 2),
axis.line.y = element_line(color="black", size = 2))
The above options do not work for maps created with sf and geom_sf(). Hence, I want to add the relevant ndiscr parameter here. This will create a nice clean map showing only the features.
library(sf)
library(ggplot2)
ggplot() +
geom_sf(data = some_shp) +
theme_minimal() + # white background
theme(axis.text = element_blank(), # remove geographic coordinates
axis.ticks = element_blank()) + # remove ticks
coord_sf(ndiscr = 0) # remove grid in the background
Simplification from the above Andrew's answer leads to this key theme to generate the half border.
theme (panel.border = element_blank(),
axis.line = element_line(color='black'))
Here's an extremely simple answer
yourPlot +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
It's that easy. Source: the end of this article
You may be check also panel.background as well.
theme(
panel.background = element_rect(fill = "black"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank()

Resources