在ggplot2中为线型图例添加附加线

时间:2018-02-22 17:39:06

标签: r ggplot2 legend

我很难为使用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

Plot #1

第二段代码创建了一条虚线,我试图在图例中标记,遗憾的是没有运气。

我很感激有关如何向图例添加第二个线型的任何指针,表示虚线。

谢谢

1 个答案:

答案 0 :(得分:0)

在第二个geom_line中,您在linetype中定义aes一次,然后立即用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"))

此外,您可以通过在主aes位中仅保留公共 ggplot参数并将特定于行的参数移动到第一个{{}}来使其更清晰一些{1}}:

geom_line

要在此之后指定线型,​​请使用ggplot(foo, aes(x = a)) + geom_line(aes(y = b, linetype = "b")) + geom_line(aes(y = c, linetype = "c"))

scale_linetype_manual