Overriding panel.grid in ggplot2 - r

The following code first drops the X-axis text, and then adds it back in with a red color:
p_text <- qplot(data = mtcars, x = hp, y = disp) +
theme(axis.text.x = element_blank())
p_text + theme(axis.text.x = element_text(colour = "red"))
Similarly, one would expect this code to do the same thing for the grid lines:
p_grid <- qplot(data = mtcars, x = hp, y = disp) +
theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "red"))
However, it only appears to add them back with default colors. Why this strange behavior, and is there a way to add the panel grid lines back in? (My actual example involves overriding various pre-set themes, so just setting the grid lines right away is not an option).

If you look at theme_grey you can see that panel.grid.minor and panel.grid.major are both specified. When you specify panel.grid to a specific color, the minor and major grid lines would inherit this if a color wasn't specified for them. But there is.
This works as expected:
p_grid <- qplot(data = mtcars, x = hp, y = disp) +
theme(panel.grid = element_blank())
p_grid + theme(panel.grid = element_line(colour = "blue"), #needed to overwrite element_blank
panel.grid.major = element_line(colour = "red"),
panel.grid.minor = element_line(colour = "red"))
and this too:
p_grid + theme(panel.grid = element_line(colour = "red"),
panel.grid.major = NULL,
panel.grid.minor = NULL)

Related

R ggplot2: Plot geom_point with black and white without using shape?

I would like to plot in black and white with ggplot2 however I don't want to use shape (ie solid black vs open black outline) because I need the shape to describe another group.
library(ggplot2)
str(mtcars)
p <- ggplot(data = mtcars, aes(x = wt, y=mpg, col=factor (vs), shape= factor (cyl) ))
p + geom_point(size=10) +
theme_bw() +
theme(legend.position="bottom", legend.title=element_blank(), legend.key = element_blank(),
axis.text.x = element_text(size=17),
axis.text.y = element_text(size=17),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.text =element_text(size=22)
) +
scale_colour_manual(values = c("red", "blue"))
The plot looks like this.
I would like to have 0 and 1 be plotted as black and white (black outline) however in this case its difficult since the shape has already been taken with factor (vs). Is there any other thing I can do? thanks.
If you want two separate legends for the two factors as you have in your example, you can use "fillable" shapes and the fill aesthetic instead of the color aesthetic. Shapes are shown here; the fillable ones are the ones in yellow, 21-25.
To get your legends to look how you want them, particularly the fill legend, you can override the shape via override.aes in guide_legend. Here I also fill the shape legend in black, but that isn't necessary if you don't mind the white legend.
ggplot(data = mtcars, aes(x = wt, y=mpg, fill = factor(vs), shape = factor (cyl)
)) +
geom_point(size=10) +
theme_bw() +
scale_fill_manual(values = c("black", "white")) +
scale_shape_manual(values = c(21, 24, 22) ) +
guides(fill = guide_legend(override.aes = list(shape = 21) ),
shape = guide_legend(override.aes = list(fill = "black" ) ) )
Here's a solution:
str(mtcars)
p <- ggplot(data = mtcars, aes(x = wt, y=mpg, shape=paste0(vs,cyl) ))
p + geom_point(size=10) +
theme_bw() +
theme(legend.position="bottom", legend.title=element_blank(), legend.key = element_blank(),
axis.text.x = element_text(size=17),
axis.text.y = element_text(size=17),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
legend.text =element_text(size=22)
)+scale_shape_manual(values = c("04"=15,"06"=16,"08"=17,"14"=0,"16"=1,"18"=2))

ggplot2: Boxplots with points and fill separation [duplicate]

This question already has answers here:
ggplot2 - jitter and position dodge together
(2 answers)
Closed 6 years ago.
I have a data which can be divaded via two seperators. One is year and second is a field characteristics.
box<-as.data.frame(1:36)
box$year <- c(1996,1996,1996,1996,1996,1996,1996,1996,1996,
1997,1997,1997,1997,1997,1997,1997,1997,1997,
1996,1996,1996,1996,1996,1996,1996,1996,1996,
1997,1997,1997,1997,1997,1997,1997,1997,1997)
box$year <- as.character(box$year)
box$case <- c(6.40,6.75,6.11,6.33,5.50,5.40,5.83,4.57,5.80,
6.00,6.11,6.40,7.00,NA,5.44,6.00, NA,6.00,
6.00,6.20,6.40,6.64,6.33,6.60,7.14,6.89,7.10,
6.73,6.27,6.64,6.41,6.42,6.17,6.05,5.89,5.82)
box$code <- c("L","L","L","L","L","L","L","L","L","L","L","L",
"L","L","L","L","L","L","M","M","M","M","M","M",
"M","M","M","M","M","M","M","M","M","M","M","M")
colour <- factor(box$code, labels = c("#F8766D", "#00BFC4"))
In boxplots, I want to display points over them, to see how data is distributed. That is easily done with one single boxplot for every year:
ggplot(box, aes(x = year, y = case, fill = "#F8766D")) +
geom_boxplot(alpha = 0.80) +
geom_point(colour = colour, size = 5) +
theme(text = element_text(size = 18),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
legend.position = "none")
But it become more complicated as I add fill parameter in them:
ggplot(box, aes(x = year, y = case, fill = code)) +
geom_boxplot(alpha = 0.80) +
geom_point(colour = colour, size = 5) +
theme(text = element_text(size = 18),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
legend.position = "none")
And now the question: How to move these points to boxplot axes, where they belong? As blue points to blue boxplot and red to red one.
Like Henrik said, use position_jitterdodge() and shape = 21. You can clean up your code a bit too:
No need to define box, then fill it piece by piece
You can let ggplot hash out the colors if you wish and skip constructing the colors factor. If you want to change the defaults, look into scale_fill_manual and scale_color_manual.
box <- data.frame(year = c(1996,1996,1996,1996,1996,1996,1996,1996,1996,
1997,1997,1997,1997,1997,1997,1997,1997,1997,
1996,1996,1996,1996,1996,1996,1996,1996,1996,
1997,1997,1997,1997,1997,1997,1997,1997,1997),
case = c(6.40,6.75,6.11,6.33,5.50,5.40,5.83,4.57,5.80,
6.00,6.11,6.40,7.00,NA,5.44,6.00, NA,6.00,
6.00,6.20,6.40,6.64,6.33,6.60,7.14,6.89,7.10,
6.73,6.27,6.64,6.41,6.42,6.17,6.05,5.89,5.82),
code = c("L","L","L","L","L","L","L","L","L","L","L","L",
"L","L","L","L","L","L","M","M","M","M","M","M",
"M","M","M","M","M","M","M","M","M","M","M","M"))
ggplot(box, aes(x = factor(year), y = case, fill = code)) +
geom_boxplot(alpha = 0.80) +
geom_point(aes(fill = code), size = 5, shape = 21, position = position_jitterdodge()) +
theme(text = element_text(size = 18),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_blank(),
legend.position = "none")
I see you've already accepted #JakeKaupp's nice answer, but I thought I would throw in a different option, using geom_dotplot. The data you are visualizing is rather small, so why not forego the boxplot?
ggplot(box, aes(x = factor(year), y = case, fill = code))+
geom_dotplot(binaxis = 'y', stackdir = 'center',
position = position_dodge())

ggplot classic theme missing axes [duplicate]

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.

How to display the horizontal line completely using ggplot2?

I have asked a question earlier.Here is the link:how to add a vertical line using theme() function in my plot
And now new problem happened,the horizontal line of the band6 can not display completely.Anyone can give me some suggestions?Thank you.
And my code is below:
p <- ggplot(data = df1, aes(x = df1$MeanDecreaseAccuaracy, y = reorder(factor(df1$Variables),df1$MeanDecreaseAccuaracy)))
p + geom_segment(aes(yend = df1$Variables,xend = 0)) +
geom_point() +
theme_minimal() +
scale_x_continuous(expand = c(0,0),breaks = c(5,10,15,20,25,30,35,40,45)) +
labs(x = "Mean Decrease in Accuracy",y = "Prdictors variable") +
theme(axis.line = element_line(colour = "black"),
axis.text.x = element_text(colour = "black"),
axis.text.y = element_text(colour = "black"),
axis.ticks.x = element_line(size = 0.2,colour = "black"),
axis.ticks.y = element_line(size = 0.2,colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
And the output figure is as follows.
Okay, posting as answer:
Don't use data$column inside aes(). It will cause problems if you try to facet or use other advanced features. You should have
aes(x = MeanDecreaseAccuracy,
y = reorder(factor(Variables, MeanDecreaseAccuracy)))
To solve your problem, I would recommend setting limits = c(0, 1.05 * max(df1$MeanDecreaseAccuracy)). inside your scale_x_continuous. (Note that is not inside aes() so you do need to use the data$column identifier here).

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