How to add a legend to hline?
You can use the linetype
aesthetic to make a separate legend for the horizontal lines rather than adding them to the existing legend.
To do this we can move linetype
inside aes
while still mapping to a constant. I used your desired labels as the constant. The legend name and the line type used can be set in scale_linetype_manual
. I remove show.legend = TRUE
to keep the lines out of the other legend. The legend colors are fixed in override.aes
.
I + geom_hline(aes(yintercept= 10, linetype = "NRW limit"), colour= 'red') +
geom_hline(aes(yintercept= 75.5, linetype = "Geochemical atlas limit"), colour= 'blue') +
scale_linetype_manual(name = "limit", values = c(2, 2),
guide = guide_legend(override.aes = list(color = c("blue", "red"))))
How to add the legend for hline in ggplot2
One option to achieve your desired result would be to map on aesthetics and make use of scale_xxx_manual
instead of setting the color, linetypes, ... via arguments:
month=c("Jan","Feb","Mar","Apr","May","Jun")
rate=c(70,80,90,85,88,76)
dd=data.frame(month,rate)
dd$type="Rate"
dd$month=factor(dd$month)
library(ggplot2)
ggplot(dd,aes(x=month,y=rate, color="Rate", linetype = "Rate")) +
geom_point(aes(x=month,y=rate, shape = "Rate"), size=2) +
geom_text(aes(label = paste(format(rate, digits = 4, format = "f"), "%")),
color="black",vjust = -0.5, size = 3.5) +
geom_line(aes(x = month, y = rate, group=1, size = "Rate")) +
geom_hline(aes(yintercept=85, color = "Target", linetype = "Target", size = "Target")) +
labs(y = NULL, x= NULL, color = NULL, linetype = NULL, shape = NULL, size = NULL) +
scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +
scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +
scale_shape_manual(values = c(Rate = 16, Target = NA)) +
scale_size_manual(values = c(Rate = 1, Target = .5)) +
theme(legend.position="bottom")
Add geom_hline to legend
Given solution works in most of the cases, but not for geom_hline
(vline
). For them you usually don't have to use aes
, but when you need to generate a legend then you have to wrap them within aes
:
library(ggplot2)
ggplot() +
geom_line(aes(count, mean, color = "TrueMean"), myDf) +
geom_hline(aes(yintercept = myTrueMean, color = "SampleMean")) +
scale_colour_manual(values = c("red", "blue")) +
labs(title = "Plot showing convergens of Mean",
x = "Index",
y = "Mean",
color = NULL) +
theme_minimal()
Seeing original data you can use geom_point
for better visualisation (also added some theme changes):
ggplot() +
geom_point(aes(count, mean, color = "Observed"), myDf,
alpha = 0.3, size = 0.7) +
geom_hline(aes(yintercept = myTrueMean, color = "Expected"),
linetype = 2, size = 0.5) +
scale_colour_manual(values = c("blue", "red")) +
labs(title = "Plot showing convergens of Mean",
x = "Index",
y = "Mean",
color = "Mean type") +
theme_minimal() +
guides(color = guide_legend(override.aes = list(
linetype = 0, size = 4, shape = 15, alpha = 1))
)
How can I add legend to multiple hlines in ggplot2?
To show a legend in a ggplot
, you should create an aesthetic mapping. The simplest way to do that is to have a seperate little data frame that contains the information you want to show on your hline
s.
You haven't provided any sample data, so I've made some up here so that this is a fully reproducible example:
library(ggplot2)
set.seed(69)
main_data <- data.frame(x = rnorm(200, 10), y = rnorm(200, 10))
hline_data <- data.frame(y = c(8, 10, 12), type = factor(c(2, 1, 2)),
stringsAsFactors = FALSE)
ggplot(main_data, aes(x,y)) +
geom_point() +
geom_hline(data = hline_data,
aes(yintercept = y, linetype = type, colour = type)) +
scale_colour_manual(values = c("blue", "red"),
labels = c("Recommended Spacing", "Limits of spacing"),
name = "Key") +
scale_linetype_manual(values = 1:2,
labels = c("Recommended Spacing", "Limits of spacing"),
name = "Key")
Created on 2020-05-19 by the reprex package (v0.3.0)
how to add and edit a legend in goem_hline() in R
Update: OP request:
p <- ggplot(data=df, aes(x=year_date, y=total, fill=name))+
geom_col(position = "dodge")+
scale_fill_manual(values=c("#08088A","#9F81F7"))+
theme_light()+labs(fill="rain", title ="rain anual", x="Estation", y="total mm")+
theme(axis.text.x = element_text(angle = 90))
data_line <- data.frame(yintercept=18, data_line=factor(18))
p +
geom_hline(data=data_line, aes(yintercept=yintercept, linetype="18"), size=1.5, col="#ffff00") +
scale_linetype_manual(name = "Historiacal serie",values = c(1,1))
Add geom_hline legend to existing geom bar legend
As @Gregor suggested, you could use a direct label for this line by adding annotate()
as shown below:
ggplot(df, aes(x=Outcome2, y=d, fill=study)) +
geom_bar(position=position_dodge(), aes(x=Outcome2),stat="identity",
colour="black", # Use black outlines,
size=.3) + # Thinner lines
xlab("Outcome") +
ylab("Cohen's D Effect Size") +
scale_fill_grey(name="Study",
labels=c("study1","study2", "study3"))+
theme_bw()+
geom_hline(yintercept=.15,linetype=2) +annotate("text",x=.7,y=.17,size=3,label=c('avg tx ef'))
If space is an issue you can use the wrapper
described here to wrap the text. Just run wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")
then add +annotate("text",x=.7,y=.18,size=3,label=wrapper('avg tx effect',10))
. Which produces:
Add axhline to legend
Simply using plt.legend()
tells you what data is being plotting:
You are using someBoolean
as the hue. So you are essentially creating two lines by applying a Boolean mask to your data. One line is for values that are False (shown as 0 on the legend above), the other for values that are True (shown as 1 on the legend above).
In order to get the legend you want you need to set the handles and the labels. You can get a list of them using ax.get_legend_handles_labels()
. Then make sure to omit the first handle which, as shown above, has no artist:
ax = sns.lineplot(x="x", y="y", hue="someBoolean", data=data)
plt.axhline(y=7, c='red', linestyle='dashed', label="horizontal")
labels = ["some name", "some other name", "horizontal"]
handles, _ = ax.get_legend_handles_labels()
# Slice list to remove first handle
plt.legend(handles = handles[1:], labels = labels)
This gives:
How to add a custom legend for geom_hline
It's a bit awkward, but this seems to work:
hline <- data.frame(yint = 0.136,lt = 'Avg')
ggplot(data=df[df$lang=="en",])+
geom_point(aes(x=days,y=points),size=5,colour='cyan')+
geom_point(aes(x=days,y=points,colour=days),size=4)+
facet_wrap(~lang,ncol=1,scales="free")+
xlab("")+
ylab("")+
scale_y_continuous(labels = percent_format())+
theme(legend.position="right",
legend.title = element_blank(),
strip.text.x = element_text(size = 13, colour = 'black', angle = 0),
axis.text.x=element_text(angle=0, hjust=.5, vjust=0),
legend.position = 'none',
panel.background = element_rect(fill = "#545454"),
panel.grid.major = element_line(colour = "#757575"),
panel.grid.minor = element_line(colour = "#757575"))+
geom_hline(data = hline,aes(yintercept=yint,linetype = lt),color = "cyan",size=2,show_guide = TRUE) +
scale_colour_discrete(guide = "none") +
scale_linetype_manual(name = 'Legend',values = 1,guide = "legend")
Ah, but you've included legend.title = element_blank()
in there, which is why the legend is not named. Remove that to include the name.
In ggplot2, how to display a legend using geom_hline function?
geom_hline
is special: its show_guide
argument is FALSE
by default, in contrast to most other geoms (presumably because geom_hline
is so often used for annotation ...)
You didn't give a reproducible example before I initially answered the question, but this slightly hacked example seems to work:
library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y=mpg)) + geom_point()
p + geom_hline(aes(lty="foo",yintercept=20),show_guide=TRUE)+
scale_linetype_manual(name="",values=2)
The ugliness is because there needs to be something to show in the guide (legend); just saying geom_hline(yintercept=20,lty=2,show_guide=TRUE)
doesn't work. There's probably a more principled way to do this, though.
Related Topics
Keyed Lookup on Data.Table Without 'With'
Compute the Minimum of a Pair of Vectors
Special Characters and Superscripts on Plot Axis Titles
Reproduce Table and Plot from Journal
Fast Reading and Combining Several Files Using Data.Table (With Fread)
Fast Large Matrix Multiplication in R
How to Create Vectors with Specific Intervals in R
R for Loop Skip to Next Iteration Ifelse
Calculating Number of Days Between 2 Columns of Dates in Data Frame
Joining Means on a Boxplot with a Line (Ggplot2)
How to Subset a Matrix with Different Column Positions for Each Row
Calculate Total Miles Traveled from Vectors of Lat/Lon
One Function to Detect Nan, Na, Inf, -Inf, etc.
How to Calculate the Probability for a Given Quantile in R
Example Needed: Change the Default Print Method of an Object