[英]How to add legend to a combined line+box graph in ggplot2()
我有一個帶有以下信息的 dataframe
但是我使用了下面的代碼 plot 它(繪制的圖表顯示在評論后面),但不知道如何為這個組合(線和條)plot 添加圖例。
#plot with ggplot2
ggplot(data) +
geom_col(aes(x=cluster_number, y=2*reduction_in_withincluster_variation), fill="grey", colour="black")+
geom_line(aes(x=cluster_number, y=within_cluster_variation), size=1)+
geom_point(aes(x=cluster_number, y=within_cluster_variation), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters")+
scale_y_continuous(breaks=seq(0, 0.14, 0.02), sec.axis = sec_axis(~./2, breaks=seq(0, 0.07, 0.01), name = "Reduction in within-cluster variation"))+
theme_classic(base_size = 13)
任何建議都會非常有幫助
謝謝!
plot 目前看起來像這樣,我想為圖表右側的線和條添加一個圖例。
要為給定的幾何圖形顯示圖例,您需要分配將在aes()
內的圖例中表示的內容。 通常,這將應用於數據中的列,並根據該數據中每個觀察值的值創建圖例鍵條目並分配 colors。 但是,您也可以在aes()
中將字符串分配給諸如fill=
或color=
或linetype=
之類的美學。 這將產生為該特定幾何創建圖例鍵條目並將該美學條目添加到具有該名稱的圖例的效果。
我們可以將此方法應用於 OP 的示例。 他們沒有共享數據,但這里有一個模擬 OP 顯示的數據的示例(沒有輔助 y 軸的東西等):
library(ggplot2)
data <- data.frame(
cluster_number = 1:16,
points_and_lines = c(0.14, 0.077, 0.052, 0.045, 0.038, 0.035, 0.033, 0.032, 0.032, 0.031, 0.029, 0.028, 0.027, 0.025, 0.024, 0.022),
bar_heights = c(0.12, 0.04, 0.02, 0.018, 0.012, 0.01, 0.008, 0.007, 0.007, 0.006, 0.004, 0.004, 0.004, 0.003, 0.002, 0.001)
)
p <- ggplot(data) +
geom_col(aes(x=cluster_number, y=bar_heights), fill="grey", colour="black")+
geom_line(aes(x=cluster_number, y=points_and_lines), size=1)+
geom_point(aes(x=cluster_number, y=points_and_lines), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters")+
theme_classic(base_size = 13)
p
這是上述策略的應用。 在這種情況下,我想對列使用fill=
,而對線和點使用color=
。 這將具有組合線的圖例鍵中的外觀+“線和點”的點並為列顯示灰色框的凈效果。 如果您只想要“線和點”的圖例中的線或點條目,則可以僅將一個或另一個放入aes()
。
請注意,我們不僅需要在aes()
中為幾何圖形添加fill
和color
,而且還需要:(1)使圖例標題為NULL
以避免出現圖例標題(除非您想要它),以及(2)定義實際的 colors,否則, ggplot2
將 map 將它們設置為默認色調比例。
ggplot(data) +
geom_col(aes(x=cluster_number, y=bar_heights, fill="bars"), colour="black")+
geom_line(aes(x=cluster_number, y=points_and_lines), size=1)+
geom_point(aes(x=cluster_number, y=points_and_lines, color="lines and points"), pch =16)+
scale_x_continuous(breaks=seq(1, 16, 1)) +
labs(y = "Within-cluster variation", x = "Number of clusters", color=NULL, fill=NULL)+
scale_fill_manual(values="grey") +
scale_color_manual(values="black") +
theme_classic(base_size = 13) +
theme(legend.position="top")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.