Reputation:
I just started R programming 2 weeks ago and i have a case study plot with 1 x axis and 2 y axis... I tried everything i can for 48 hours to replace Title with Legend... And i couldn't figure out what's the issue, Hopefully i can get help input from you guys.
PLOT:
ggplot(libya_covid, aes(x=date)) +
geom_line( aes(y=new_tests), size=2, color='blue') +
geom_line( aes(y=new_cases / 1), size=2, color='darkorange') +
xlab("Date")+
scale_y_continuous(
# Features of the first axis
name = "New Tests",
# Add a second axis and specify its features
sec.axis = sec_axis(~.*1, name= "New Cases")
) +
theme_bw() +
theme(
axis.title.y = element_text(color = 'blue', size=13),
axis.title.y.right = element_text(color = 'darkorange', size=13)
) +
ggtitle("New Tests Versus New Cases Analysis")
Now I just Want To Remove Y Titles from Right & Left and ADD Simple Legend On Top Left
Thanks in Advance.
Upvotes: 3
Views: 2763
Reputation: 124213
In ggplot2 legends reflect aesthetics or scales. This said, if you want to have a legend you have to map on aesthetics.
To get a legend depicting the different colored lines you could map a constant value on the color aesthetic and then assign your desired colors to these constants using scale_color_manual
.
To get rid of the labels remove the name=
s from scale_y_continious
and using labs
set y=NULL
which means remove the y axis title. Finally, you could position the legend via theme
options legend.position
and legend.justification
:
library(ggplot2)
#### Use economics dataset as example data
libya_covid <- ggplot2::economics
names(libya_covid)[4:5] <- c("new_tests", "new_cases")
####
ggplot(libya_covid, aes(x=date)) +
geom_line( aes(y=new_tests, color='New Tests'), size=2) +
geom_line( aes(y=new_cases / 1, color='New Cases'), size=2) +
labs(x = "Date", y = NULL, color = NULL, title = "New Tests Versus New Cases Analysis") +
scale_y_continuous(
sec.axis = sec_axis(~.*1)
) +
scale_color_manual(values = c("New Tests" ='blue', "New Cases" ='darkorange')) +
theme_bw() +
theme(
axis.title.y = element_text(color = 'blue', size=13),
axis.title.y.right = element_text(color = 'darkorange', size=13),
legend.position = c(0.05, .95),
legend.justification = c(0.05, .95)
)
Upvotes: 2