簡體   English   中英

向ggplot2中的線型圖例添加其他行

[英]Adding Additional Lines to Linetype Legend in ggplot2

對於使用ggplot2在R中創建的繪圖,我很難在圖例中添加其他線型。 以下代碼對變量Percentage.of.Total.Prescriptions....Percentage.Paid.Out.of.Pocket....使用連續數據,以嘗試創建具有兩組實線和虛線的線圖,和一個各自的傳說。

Lineplot <- ggplot(Table.6, aes(x = Year, 
                            y = Percentage.of.Total.Prescriptions...., 
                            group = as.factor(Table.6$Insurance.Status), 
                            color = Insurance.Status,
                            linetype = "Total Insulin \nPrescriptions")) + geom_line()
Lineplot <- Lineplot + 
geom_line(aes(y = Percentage.Paid.Out.of.Pocket...., 
colour = Insurance.Status, 
linetype = "Paid \n Out-of-Pocket"), 
linetype = 5)

Lineplot <- Lineplot + labs(title = "Human Insulin Utilization")
Lineplot <- Lineplot + labs(x = "Year")
Lineplot <- Lineplot + labs(y = "Percentage (%)")
Lineplot <- Lineplot + labs(colour = "Insurance Status")
Lineplot <- Lineplot + scale_x_continuous(breaks = c(seq(2002,2015,1)))
Lineplot <- Lineplot + scale_y_continuous(breaks = c(seq(0,1,0.1)))
Lineplot <- Lineplot + expand_limits(y = 0:1)
Lineplot

情節#1

第二段代碼創建了一個虛線,我試圖在圖例中將其標記為不幸的是沒有運氣。

我希望您能對圖例中的虛線表示第二種線型有所指點。

謝謝

在第二個geom_line ,您要在aes定義一次linetype ,然后立即用linetype = 5覆蓋它。 刪除它,它應該可以工作:

# dummy data
foo = data.frame(a = c(1:10),
                 b = rnorm(10, 5, 2),
                   c = rnorm(10,10,2))

# how it is now
ggplot(foo, aes(x = a, y = b, linetype = "b")) + 
  geom_line() + 
  geom_line(aes(y = c, linetype = "c"), linetype = 5)

# fixed
ggplot(foo, aes(x = a, y = b, linetype = "b")) + 
  geom_line() + 
  geom_line(aes(y = c, linetype = "c"))

另外,您可以通過在main ggplot位中僅保留common aes參數並將特定於行的參數移至第一個geom_line來使其更geom_line

ggplot(foo, aes(x = a)) + 
  geom_line(aes(y = b, linetype = "b")) + 
  geom_line(aes(y = c, linetype = "c"))

要在此之后指定線型,​​請使用scale_linetype_manual

ggplot(foo, aes(x = a)) + 
  geom_line(aes(y = b, linetype = "b")) + 
  geom_line(aes(y = c, linetype = "c")) + 
  scale_linetype_manual(values = c(1,5))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM