Add Label in Line chart in R - r

I am trying to add labels in line graph but am unable to do so.
I want to add lable such that blue line mentiones 'model_1'; red line mentioned 'model_2' and darkgreen line mentioned 'model_3'
Attaching the code below
p1 <- ggplot(data = Auto, aes(x = horsepower, y = mpg)) +
geom_point() +
geom_line(aes(y = fitted(lm_mpg_1)), color = "blue", size = 1) +
geom_line(aes(y = fitted(lm_mpg_2)), color = "red", size = 1) +
geom_line(aes(y = fitted(lm_mpg_3)), color = "darkgreen", size = 1)
I have tried to use geom_text, geom_label and annotate function however they give me error.
The code I tried was:
p1 + geom_text(label = c('model_1','model_2','model_3'))

You don't have any data. You can use dput to share your data. In the meanwhile I have used mtcars as an example below:
# library
library(ggplot2)
# Keep 30 first rows in the mtcars natively available dataset
data=head(mtcars, 30)
# 1/ add text with geom_text, use nudge to nudge the text
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_text(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
ggplot(data, aes(x=wt, y=mpg)) +
geom_point() + # Show dots
geom_label(
label=rownames(data),
nudge_x = 0.25, nudge_y = 0.25,
check_overlap = T
)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 4, y = 25, label = "Some text")

Related

mean line in every facet_wrap

ggplot(data = results, aes(x = inst, y = value, group = inst)) +
geom_boxplot() +
facet_wrap(~color) +
#geom_line(data = mean,
#mapping = aes(x = inst, y = average, group = 1))
theme_bw()
When I run the code above with the code line commented, it runs and gives the graph below but I want a joining mean lines on the boxplots based on its own color category for each group in facet wraps. Any ideas how can I do that?
Your code is generally correct (though you'll want to add color = color to the aes() specification in geom_line()), so I suspect your mean dataset isn't set up correctly. Do you have means grouped by both your x axis and faceting variable? Using ggplot2::mpg as an example:
library(dplyr) # >= v1.1.0
library(ggplot2)
mean_dat <- summarize(mpg, average = mean(hwy), .by = c(cyl, drv))
ggplot(mpg, aes(factor(cyl), hwy)) +
geom_boxplot() +
geom_line(
data = mean_dat,
aes(y = average, group = 1, color = drv),
linewidth = 1.5,
show.legend = FALSE
) +
facet_wrap(~drv) +
theme_bw()
Alternatively, you could use stat = "summary" and not have to create a means dataframe at all:
ggplot(mpg, aes(factor(cyl), hwy)) +
geom_boxplot() +
geom_line(
aes(group = 1, color = drv),
stat = "summary",
linewidth = 1.5,
show.legend = FALSE
) +
facet_wrap(~drv) +
theme_bw()
# same result as above

Underline effect for graph and text using ggplot2

Do you know how to add the yellow highlight effect of this 538 graph for both text and graphs using ggplot2?
Thanks in advance!
Update after clarification
It really depends on the structure of the data and what you are using to plot. However, if you wanted to add large highlights to particular plots, then you could plot the same geom_line but change the aesthetics of it (though the highlight will not connect to adjacent plots).
library(ggplot2)
hlines <- mtcars %>%
group_by(cyl) %>%
summarise(MN = min(wt))
ggplot(mtcars) +
geom_line(aes(mpg, wt), colour = "lightyellow", size = 80) +
geom_line(aes(mpg, wt)) +
geom_hline(
data = hlines,
aes(yintercept = MN),
linetype = "dotted",
color = "grey",
size = 1.5
) +
facet_wrap( ~ cyl) +
theme_bw()
Output
For text, in ggplot2, you can add fill to the background of annotations. But it again really depends on the structure and how you are plotting the text. You could split up the annotations, so that you could fill one and not the other part of the text.
ggplot(mtcars) +
geom_line(aes(mpg, wt), colour = "lightyellow", size = 80) +
geom_line(aes(mpg, wt)) +
annotate(
geom = "text",
x = 30,
y = 5,
label = "It hasn't really dropped off"
) +
annotate(
geom = "label",
x = 30,
y = 4.75,
label = "since he first won office in 2016",
fill = "lightyellow",
label.size = NA
)
Output
First Answer
It depends on what exactly you are looking for/what your data looks like. But if you are wanting to place a line at the minimum under a line graph in a faceted plot, then you could do something like this:
library(ggplot2)
hlines <- mtcars %>%
group_by(cyl) %>%
summarise(MN = min(wt))
ggplot(mtcars) +
geom_line(aes(mpg, wt)) +
geom_hline(
data = hlines,
aes(yintercept = MN),
linetype = "dotted",
color = "grey",
size = 1.5
) +
facet_wrap( ~ cyl) +
theme_bw()
Output
If you just have a single plot, then you can use geom_hline and just provide the y intercept.
ggplot(mtcars) +
geom_line(aes(mpg, wt)) +
geom_hline(yintercept = 3.5,
linetype = "dotted",
color = "grey",
size = 1.5
) +
theme_bw()

How to use ggplot2 legend to denote different geoms

I am using ggplot2 to plot points from a .csv file that is just a column used a x values and a column used a y values. I am a little confused as to how ggplot decides what to make a legend for and haven't found any good examples online.
I would like the legend to show that geom_point is stress vs strain, and my geom_smooth is the best fit line.
Here is my code:
library(ggplot2)
imported = read.csv("data.csv")
Strain = imported$Strain
Stress = imported$Stress..N.m.2.
err = .0005
gg <-
ggplot(imported, aes(x=Strain, y=Stress)) +
geom_point(aes(group = "Points"), shape = 79, colour = "black", size = 2, stroke = 4) +
geom_smooth(method = "lm", se = FALSE, color = "orange") +
geom_errorbarh(xmin = Strain - err, xmax = Strain + err, show.legend = TRUE) +
theme_gray() + ggtitle("Stress vs Strain") +
theme(legend.position = "top")
gg
And it is producing the following plot:
my plot
Edit: added approach at top to create legend for each geom, by creating dummy mapping to separate aesthetics.
library(ggplot2)
ggplot(mtcars, aes(mpg, wt)) +
geom_point(aes(color = "point")) + # dummy mapping to color
geom_smooth(method = "lm", se = FALSE, color = "orange",
aes(linetype = "best fit")) + # dummy mapping to linetype
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1)) +
scale_color_manual(name = "Stress vs. Strain", values = "black") +
scale_linetype_manual(name = "Best fit line", values = "solid")
original answer:
Note the difference in legend here:
library(ggplot2)
ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
geom_point() +
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1),
show.legend = TRUE) # error bars reflected in legend
ggplot(mtcars, aes(mpg, wt, color = as.character(cyl))) +
geom_point() +
geom_errorbarh(aes(xmin = mpg - 2, xmax = mpg + 1),
show.legend = FALSE) # error bars not shown in legend

Misaligned dots in ggplot2's dotplot in R

I don't understand why the dots for ID 2,6,8,10 won't align vertically like they do in 1,3,4,7,9.
The offset is affected by stackratio, but why doesn't it affect all the groups?
ggplot(sleep,
aes(x=ID,fill=group,y=extra))+
geom_dotplot(binaxis = 'y',
method="histodot",
stackgroups = TRUE,
binpositions="bygroup",
stackratio=1,
binwidth=0.1,
stackdir = "center",
dotsize = 3)
Another example is
ggplot(mtcars, aes(x = factor(am),fill = factor(cyl), y = mpg)) +
geom_dotplot(binaxis = "y",stackgroups = TRUE, stackdir = "center", binpositions="all")
Here stackgroups = TRUE makes everything offset weirdly.
Can something be done here, or is there another way to get the samme?
It seems that geom_dotplot calculates "dodge" positions as if all the dots were in one group and then plots them in each group.
I found work around.
Here i make a plot and color the dots myself. This ggplot can not make a legend for, so I make another plot that was the right legend.
Then use plot_grid to make my final plot.
It is important to setkey right, or the plot will be colored incorrect.
mycars <- as.data.table(mtcars)
mycars[cyl=="4",mycol:="red"][cyl=="6",mycol:="green"][cyl=="8",mycol:="blue"]
setkey(mycars,am,mpg)
myplot <- ggplot(mycars, aes(x = factor(am), y = mpg)) +
geom_dotplot(binaxis = "y",
fill=mycars$mycol,
stackratio=1,
binwidth=0.7, drop=FALSE,
stackdir = "center",
dotsize = 1)
lplot <- ggplot(mtcars, aes(x = factor(am),fill = factor(cyl), y = mpg))+
geom_dotplot(binaxis = "y",stackgroups = TRUE)+
scale_fill_manual(values=c("red","green", "blue"))
mylegend <- get_legend(lplot)
plot_grid(myplot,mylegend,ncol=2,rel_widths = c(6,1))
Plot
I cannot tell you what's the issue when using the geom_dotplot function, but you can get what you want by using geom_point and the option position = position_dodge2(). Inside the function position_dodge2() you can use width to control the position of each point. See the full code below:
library(ggplot2)
ggplot(sleep,
aes(x=ID,fill=group,y=extra))+
geom_point(
size=3,
pch = 21,
position = position_dodge2(width=c(rep(0.00001,4),
0.2,
rep(0.00001,5)))
) +
scale_y_continuous(limits = c(-2,6)) +
theme_classic() +
theme(panel.grid.major.x = element_line(color="gray",
linetype = "dashed"))
The result:
Update
We can have different alignments within the same X. For instance, when ID=1 I can move the point for group 2 while maintaining the point for group 1:
Code:
library(ggplot2)
ggplot(sleep,
aes(x=ID,fill=group,y=extra))+
geom_point(
size=3,
pch = 21,
position = position_dodge2(width=c(0.7,
rep(0.00001,3),
0.2,
rep(0.00001,5),
0.00001,
rep(0.00001,3),
0.2,
rep(0.00001,5)))
) +
scale_y_continuous(limits = c(-2,6)) +
theme_classic() +
theme(panel.grid.major.x = element_line(color="gray",
linetype = "dashed"))

ggrepel remove line around labels

How can I remove the line around geom_label_repel. Using label.size = 0 appears to have no visible effect. I could set `colour
library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(wt, mpg, color = wt)) +
geom_point(color = 'red') +
geom_label_repel(aes(label = rownames(mtcars)), label.size = 0, fill = "white") +
theme_classic(base_size = 16)
Entering a geom_text_repel after a blank geom_label_repel occasionally works, but is not reliable: the boxes may appear in a different location to the text.
As eipi10 noted in the comment, set label.size=NA:
library(ggplot2)
library(ggrepel)
ggplot(mtcars, aes(wt, mpg, color = wt)) +
geom_point(color = 'red') +
geom_label_repel(aes(label = rownames(mtcars)), label.size = NA, fill = "white") +
theme_classic(base_size = 16)
You can omit the label boxes using the geom_text_repel geom.
library(ggplot2)
library(ggrepel)
g <- ggplot(mtcars, aes(wt, mpg, color = wt)) +
geom_point(color = 'red') +
theme_classic(base_size = 16)
g + geom_label_repel(aes(label = rownames(mtcars)), fill = "white")
g + geom_text_repel(aes(label = rownames(mtcars)))
Also, according to the help page:
Currently geom_label_repel ... is considerably slower than geom_text_repel.

Resources