如何解决在ggplot图例中区分两个数据字符串
我试图在ggplot2上绘制两条带有各自图例的线,但到目前为止未成功。我尝试在geom_line字段上通过线型区分它们,但是该图无法绘制。可能是什么原因?
Example data:
x <-
year counts amounts
2000 0 2
2001 1 2
2002 1 0
2003 0 1
2004 3 7
2005 1 11
2006 2 10
2007 2 12
2008 3 13
2009 3 15
2010 3 17
ggplot(x,aes(x = year)) +
geom_line(aes(y = counts)) +
geom_line(aes(y = amounts)) +
theme_bw()
感谢您的帮助!
解决方法
在绘制之前以长格式获取数据:
library(ggplot2)
library(dplyr)
df %>%
tidyr::pivot_longer(cols = -year) %>%
mutate(year = factor(year)) %>%
ggplot() + aes(year,value,group = name,color = name) +
geom_line() + theme_bw()
数据
df <- structure(list(year = 2000:2010,counts = c(0L,1L,0L,3L,2L,3L),amounts = c(2L,7L,11L,10L,12L,13L,15L,17L)),class = "data.frame",row.names = c(NA,-11L))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。