我 2 周前剛開始 R 編程,我有一個帶有 1 x 軸和 2 y 軸的案例研究圖……我嘗試了 48 小時的一切,用圖例替換標題……我不知道是什么這個問題,希望我能得到你們的幫助。
陰謀:
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")

現在我只想從左右洗掉 Y 標題并在左上角添加簡單的圖例
提前致謝。
uj5u.com熱心網友回復:
在 ggplot2 中,圖例反映了美學或比例。這就是說,如果你想要一個傳奇,你必須在美學上進行映射。
要獲得描繪不同顏色線條的圖例,您可以在顏色美學上映射一個常量值,然后使用scale_color_manual.
要擺脫標簽,請name=從中洗掉sscale_y_continious并使用labsset y=NULL,這意味著洗掉 y 軸標題。最后,您可以通過themeoptionslegend.position和來定位圖例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)
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/390461.html
下一篇:我們可以找到基R中的所有類嗎?
