繁体   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