抱歉,這是較早發布的,但由于是重復的問題而被洗掉。副本談到使用 scale_colour_manual 向情節添加圖例但是我無法讓它作業,我在下面添加了我的代碼,包括這個建議。感謝它在重新發布時可能會皺眉,所以一旦解決,請隨時洗掉。
我有以下情節,我希望在情節中添加一個圖例,但似乎也無法做到。如果有人知道如何做到這一點,我已經在下面包含了我的代碼和繪圖。我正在尋找紅色代表“東方”,藍色代表“西方”,黑色代表“整體”。還包括一小部分要復制的資料。我在這里查看了其他帖子,建議使用 scale_colour_manual 之類的內容,但無法使其正常作業。
使用的代碼;
ggplot(climate_df_year, aes(y = overall_sst, x = year))
geom_line()
geom_line(aes(y = eastern_sst, x = year), col = 'red', linetype = 2, size = 0.6)
geom_line(aes(y = western_sst, x = year), col = 'blue', linetype = 2, size = 0.6)
scale_colour_manual("",
breaks = c("Eastern", "Overall", "Western"),
values = c("red", "black", "blue"))
ylab("SST (°C)")
xlab("Year")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))
資料
year overall_sst eastern_sst western_sst
1998 20.3 21.3 19.0
1999 20.6 21.6 19.2
2000 20.4 21.3 19.1
陰謀

uj5u.com熱心網友回復:
我建議旋轉資料并使用 ggplot 的原生主題aes來控制顏色和線型。
tidyr::pivot_longer(climate_df_year, -year) |>
ggplot(aes(year, value))
geom_line(aes(color = name, linetype = !grepl("overall", name)))
scale_x_continuous(breaks = do.call(seq, as.list(range(dat$year))))
scale_colour_manual(name = "Something", values = c(overall_sst="black", eastern_sst="red", western_sst="blue"))
labs(x = "Year", y = "SST (°C)")
scale_linetype_discrete(guide = NULL)

也可以reshape2::melt(climate_df_year, "year", variable.name = "name")用于旋轉,否則使用相同的代碼。
但是,如果您真的不喜歡旋轉/融合您的資料,則欺騙鏈接有幾個作業更改,即將這些部分color=帶入呼叫aes(..)。如果您只是從原始代碼中執行此操作(并洗掉或更新了scale_colour_manual呼叫,因為中斷會有所不同),您會看到一個明顯的變化:
ggplot(climate_df_year, aes(y = overall_sst, x = year))
geom_line()
geom_line(aes(y = eastern_sst, x = year, col = 'red'), linetype = 2, size = 0.6)
geom_line(aes(y = western_sst, x = year, col = 'blue'), linetype = 2, size = 0.6)
scale_colour_manual("",
breaks = c("red", "Overall", "blue"),
values = c("red", "black", "blue"))
ylab("SST (°C)")
xlab("Year")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))

這兩個更改被帶入col=(原文如此)aes(..),并重命名了其中的兩個breaks=值。從那開始,一個小游戲建議添加color=到原始值geom_line(用于“整體”)并重命名所有color=值(恢復為原始scale_colour_manual.
ggplot(climate_df_year, aes(y = overall_sst, x = year))
geom_line(aes(color = 'Overall'))
geom_line(aes(y = eastern_sst, x = year, color = 'Eastern'), linetype = 2, size = 0.6)
geom_line(aes(y = western_sst, x = year, color = 'Western'), linetype = 2, size = 0.6)
scale_colour_manual("",
breaks = c("Eastern", "Overall", "Western"),
values = c("red", "black", "blue"))
ylab("SST (°C)")
xlab("Year")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))

說了這么多,我強烈建議堅持使用融化的(第一個)選項,因為它只需要一次呼叫geom_line,可以原生處理所有美學,并且可以更好地擴展(例如,附加變數)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531111.html
標籤:rggplot2
下一篇:修改ggplots的顯示順序
