我有一個資料集,其中包括非營利組織想要籌集的目標(金錢方面),旁邊的串列示他們的目標年份,然后在它旁邊他們當年實際收集/籌集了多少
我做了以下總結每年目標金額的總和以及每年實際收取的總金額:
total_goal <- aggregate(x = data$goal,by = list(year), FUN = sum)
total_collected <- aggregate(x = data$collected, by = list(year), FUN = sum)
現在我想繪制這些資料。我是這樣做的:
plot <- ggplot(data = total_collected, aes(x=Group.1, y=x, group=1))
geom_line(data = total_goal, aes(x = Group.1, y =x, color = "Total Goal"))
geom_line(data = total_collected, aes(x = Group.1, y =x, color = "Total Collected"), linetype="dotted")
geom_point(color = "orange")
scale_color_manual(name = "Legend", values = c("Total Goal" = "green", "Total Collected" = "orange"))
labs(title = "xx")
xlab("xx")
ylab("xx")
如您所見,我必須手動添加說明:
scale_color_manual(name = "Legend",
values = c("Total Goal" = "green", "Total Collected" = "orange"))
如何添加這個圖例而不像這樣手動撰寫它?這樣它就派生自資料點本身。
圖例應為目標標記為綠色,為收集的金額標記為橙色。
謝謝!
此外,也許有一種更簡單的方法來完成整個情節,我只是把它復雜化了,歡迎任何關于更簡單代碼的想法。
uj5u.com熱心網友回復:
首先,我創建了一些示例資料:
total_goal <- data.frame(Group.1 = c(1, 2, 3, 4, 5, 6),
x = c(1, 2, 5, 3, 4, 2))
total_collected <- data.frame(Group.1 = c(1, 2, 3, 4, 5, 6),
x = c(2, 4, 2, 5, 6, 1))
您可以使用以下代碼:
plot <- ggplot(data = total_collected, aes(x=Group.1, y=x, group=1))
geom_line(data = total_goal, aes(x = Group.1, y =x, color = "Total Goal"))
geom_line(data = total_collected, aes(x = Group.1, y =x, color = "Total Collected"), linetype="dotted")
geom_point(color = "orange")
scale_color_manual(name = "Legend", breaks = c("Total Goal", "Total Collected"),
values = c("Total Goal" = "green", "Total Collected" = "orange"))
labs(title = "xx")
xlab("xx")
ylab("xx")
plot
輸出圖:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443260.html
上一篇:當有兩個y變數時如何添加圖例?
下一篇:將矢量資料分組以標記折線圖
