This question already has an answer here:
How to show abline of geom_abline in legend
(1 answer)
Closed 7 years ago.
I am having trouble getting ggplot to display legends for colors and line types when they are only defined within an geom_abline.
I've added a very simple example below.
It generates the plot as shown (no legends).
I've also tried adding a scale_color_manual to the plot, but that did not appear to do the trick.
Does anybody know how to make ggplot2 display the legends?
library(ggplot2);
xy_data = data.frame(x=runif(100, min=-0.5, max=0.5),
y=runif(100, min=-0.5, max=0.5));
slope_data = data.frame(slope = c(-1, -0.5, 0.5, 1.0),
model = paste0("m", seq(1,4)),
robust = rep(c("Robust", "Non-robust"), 2))
merged_data = merge(xy_data, slope_data)
slope_plot =
ggplot()+
geom_point(data=xy_data, aes(x=x, y=y))+
geom_abline(data=slope_data, aes(intercept=0, slope=slope, color=model, linetype=robust))
ggsave(plot=slope_plot, file="no_legend_slope_plot.png")
You can try:
slope_plot = ggplot() +
geom_point(data=xy_data, aes(x=x, y=y)) +
geom_abline(data=slope_data, aes(intercept=0, slope=slope, color=model, linetype=robust), show_guide=TRUE)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm trying to add a second legend for 6 vertical lines I've added onto a ggplot2 line plot representing 1 of 2 events instead of labelling the lines using the annotate function. I've tried this code but I'm not having much look:
p<- data %>%
ggplot(aes(variable, value)) +
geom_line(aes(color = size, group = size)) +
geom_vline(xintercept = c(1,9,11), linetype="dashed") +
geom_vline(xintercept = c(5,14,17), linetype="dotted") +
scale_linetype_manual(name = 'Events',
values = c('Closures' = 3,
'Opening' = 3))
A good way to do this could be to use mapping= to create the second legend in the same plot for you. The key is to use a different aesthetic for the vertical lines vs. your other lines and points.
First, the example data and plot:
library(ggplot2)
library(dplyr)
library(tidyr)
set.seed(8675309)
df <- data.frame(x=rep(1:25, 4), y=rnorm(100, 10, 2), lineColor=rep(paste0("col",1:4), 25))
base_plot <-
df %>%
ggplot(aes(x=x, y=y)) +
geom_line(aes(color=lineColor)) +
scale_color_brewer(palette="Greens")
base_plot
Now to add the vertical lines as OP has done in their question:
base_plot +
geom_vline(xintercept = c(1,9,11), linetype="dotted",
color = "red", size=1) +
geom_vline(xintercept = c(5,14,17), linetype="dotted",
color = "blue", size=1)
To add the legend, we will need to add another aesthetic in mapping=. When you use aes(), ggplot2 expects that mapping to contain the same number of observations as the dataset specified in data=. In this case, df has 100 observations, but we only need 6 lines. The simplest way around this would be to create a separate small dataset that's used for the vertical lines. This dataframe only needs to contain two columns: one for xintercept and the other that can be mapped to the linetype:
verticals <- data.frame(
intercepts=c(1,9,11,5,14,17),
Events=rep(c("Closure", "Opening"), each=3)
)
You can then use that in code with one geom_vline() call added to our base plot:
second_plot <- base_plot +
geom_vline(
data=verticals,
mapping=aes(xintercept=intercepts, linetype=Events),
size=0.8, color='blue',
key_glyph="path" # this makes the legend key horizontal lines, not vertical
)
second_plot
While this answer does not use color to differentiate the vertical lines, it's the most in line with the Grammar of Graphics principles which ggplot2 is built upon. Color is already used to indicate the differences in your data otherwise, so you would want to separate out the vertical lines using a different aesthetic. I used some of these GG principles putting together this answer - sorry, the color palette is crap though lol. In this case, I used a sequential color scale for the lines of data, and a different color to separate out the vertical lines. I'm showing the vertical line size differently than the lines from df to differentiate more and use the linetype as the discriminatory aesthetic among the vertical lines.
You can use this general idea and apply the aesthetics as you see best for your own data.
What about geom_label?
library(tidyverse)
data <- tribble(
~x, ~label,
1, "first",
1.5, "second",
5, "third"
)
data %>%
ggplot(aes(x = x, y = 1)) +
geom_vline(aes(xintercept = x)) +
geom_label(aes(label = label))
Created on 2021-12-13 by the reprex package (v2.0.1)
This question already has answers here:
facet_wrap add geom_hline
(2 answers)
Closed 5 months ago.
So I have a faceted graph, and I want to be able to add lines to it that change by each facet.
Here's the code:
p <- ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
facet_grid(.~cyl)+
scale_color_manual(values = c('red','green','blue'))+
geom_vline(xintercept = mean(mtcars$wt))
p
So my question is, how would I get it so that the graph is showing the mean of each faceted sub-graph.
I hope that makes sense and appreciate your time regardless of your answering capability.
You can do this within the ggplot call by using stat_summaryh from the ggstance package. In the code below, I've also changed scale_colour_manual to scale_fill_manual on the assumption that you were trying to set the fill colors of the histogram bars:
library(tidyverse)
library(ggstance)
ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
stat_summaryh(fun.x=mean, geom="vline", aes(xintercept=..x.., y=0),
colour="grey40") +
facet_grid(.~cyl)+
scale_fill_manual(values = c('red','green','blue')) +
theme_bw()
Another option is to calculate the desired means within geom_vline (this is an implementation of the summary approach that #Ben suggested). In the code below, the . is a "pronoun" that refers to the data frame (mtcars in this case) that was fed into ggplot:
ggplot(mtcars, aes(x=wt))+
geom_histogram(bins = 20,aes(fill = factor(cyl)))+
geom_vline(data = . %>% group_by(cyl) %>% summarise(wt=mean(wt)),
aes(xintercept=wt), colour="grey40") +
facet_grid(.~cyl)+
scale_fill_manual(values = c('red','green','blue')) +
theme_bw()
This question already has an answer here:
ggplot2: How to specify multiple fill colors for points that are connected by lines of different colors
(1 answer)
Closed 4 years ago.
I created a violin plot in R, and I want to change part of the dots color and size. This change will be according to an attribute of True/False in the data file.
This is how I tried it:
p <- ggplot(data, aes(order,count),levels=data_levels) +
geom_point(aes(colour = actor(data$color)))+
geom_violin(draw_quantiles = c(0.5),adjust = 2,size =0.4)+
geom_jitter(height = 0, width = 0.1,size =0.6)+
coord_flip()
boolColors <- as.character(c("False"="black", "True"="red"))
boolScale <- scale_colour_manual(name="color", values=boolColors)
p1 <- p + boolScale
I tried changing the size with scale_size_manual but it didn't work.
Without the data, it is had to know exactly what is wrong. But here is an example of setting a custom colour scale for points over a violin plot.
ggplot(mtcars, aes(factor(cyl), mpg)) +
geom_violin() +
geom_jitter(height = 0, width = 0.1, aes(colour = factor(gear))) +
scale_colour_manual(name="colour", values=c("pink", "purple", "orange"))
This question already has answers here:
How can I remove the legend title in ggplot2?
(6 answers)
Closed 5 years ago.
I have seen a lot of questions regarding how to remove some elements of the legend (with guides(... = FALSE) for instance, or how to remove the titles in the legend (with theme(legend.title = element_blank())) but I can't find how to remove the title of only one element in the legend.
MWE :
df = data.frame(x = 1:5, y = 2:6, col = c(1,1,1,2,2), alpha = c(1,1,2,2,3))
ggplot(df, aes(x,y)) + geom_point(aes(fill=col, alpha=alpha))
I would like for instance just to remove the alpha title.
EDIT : I know that it is possible to tweak the things manually afterwards by making something like:
p <- ggplot(df, aes(x,y)) + geom_point(aes(fill=col, alpha=alpha))
p$labels$alpha = NULL
p
but I'd like to have it in regular ggplot2 commands, without creating a variable
You can use labs():
ggplot(df, aes(x,y)) +
geom_point(aes(fill=col, alpha=alpha)) +
labs(alpha="")
This question already has an answer here:
How to background geom_vline and geom_hline in ggplot 2 in a bubble chart
(1 answer)
Closed 6 years ago.
Is there a way to add a horizontal line to a boxplot in ggplot2, that doesn't cut through the existing plot, but only the spaces in between?
Thanks for your help...
ggplot adds up each geom one after another, so...
library(ggplot2)
df <- data.frame(x = gl(3,1), y = 1:3)
ggplot(df, aes(x,y)) +
geom_hline(yintercept = 1.5) +
geom_col(width = .5)
... places a horizontal line under the bars produced by geom_col.