x <- c(1:3)
y1 <- c(2/28,13/35,43/65)
y2 <- c(1/2, 2/13, 5/43)
df <- data.frame(x, y1, y2)
x <- c(rep(1 , 5) , rep(2 , 5) , rep(3 , 5))
condition <- rep(c("1", "2", "3", "4", "5") , 3)
y3 <- c(1, 0, 0, 0, 0, 6, 4, 1, 0, 0, 12, 13, 5, 5, 3)
df2 <- data.frame(x, y3, condition)
cols <- c("1"="grey80","2"="grey70","3"="grey60","4"="grey50","5"="grey40")
ggplot()
geom_bar(aes(fill=df2$condition, y=df2$y3, x=df2$x), position="stack", stat="identity", width = 0.5)
geom_line(mapping = aes(x = df$x, y = df$y1*50),linetype=1, size = 1, color = "black")
geom_point(mapping = aes(x = df$x, y = df$y1*50), size = 2, color = "black")
geom_text(aes(x=df$x, y=df$y1*50, label = round(df$y1, 3)),vjust = "outward", hjust = "outward",show.legend = FALSE, color="black")
geom_line(mapping = aes(x = df$x, y = df$y2*50), linetype=2, size = 1, color = "black")
geom_point(mapping = aes(x = df$x, y = df$y2*50), size = 2, color = "black")
geom_text(aes(x=df$x, y=df$y2*50, label = round(df$y2, 3)),vjust = "outward", hjust = "outward",show.legend = FALSE, color="black")
scale_y_continuous(name = "Number of cases", sec.axis = sec_axis(~./50, name = "Percentage"))
scale_x_continuous(breaks = 1:3, labels=c("2008-2011","2012-2015","2016-2019")) xlab(NULL)
scale_fill_manual(name = "Resection Index",values = cols)
theme_minimal()
我為顏色添加了圖例(切除索引)。但我不知道如何為兩條線(實線和虛線)再添加一個圖例。請問如何為線型再添加一個圖例?非常感謝!!
uj5u.com熱心網友回復:
基本上它與fill. 作為一般規則:如果你想要一個圖例,那么你必須映射美學,即移動linetype = ...inside aes(),然后通過例如設定你想要的線型scale_linetype_manual。
注意:df$...不推薦在ggplot2. 而是通過data引數傳遞您的資料,并簡單地將變數名稱映射到美學上。這也適用于多個資料幀:
cols <- c("1" = "grey80", "2" = "grey70", "3" = "grey60", "4" = "grey50", "5" = "grey40")
ltys <- c("1" = 1, "2" = 2)
library(ggplot2)
ggplot(data = df)
geom_bar(data = df2, aes(fill = condition, y = y3, x = x), position = "stack", stat = "identity", width = 0.5)
geom_line(mapping = aes(x = x, y = y1 * 50, linetype = "1"), size = 1, color = "black")
geom_point(mapping = aes(x = x, y = y1 * 50), size = 2, color = "black")
geom_text(aes(x = x, y = y1 * 50, label = round(y1, 3)), vjust = "outward", hjust = "outward", show.legend = FALSE, color = "black")
geom_line(mapping = aes(x = x, y = y2 * 50, linetype = "2"), size = 1, color = "black")
geom_point(mapping = aes(x = x, y = y2 * 50), size = 2, color = "black")
geom_text(aes(x = x, y = y2 * 50, label = round(y2, 3)), vjust = "outward", hjust = "outward", show.legend = FALSE, color = "black")
scale_y_continuous(name = "Number of cases", sec.axis = sec_axis(~ . / 50, name = "Percentage"))
scale_x_continuous(breaks = 1:3, labels = c("2008-2011", "2012-2015", "2016-2019"))
xlab(NULL)
scale_fill_manual(name = "Resection Index", values = cols)
scale_linetype_manual(name = "NAME", values = ltys)
theme_minimal()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/325056.html
上一篇:如何使用R繪制世界地圖
