英文:
ggplot2: remove alphabetic order in the legend after the pivot of the dataset
问题
这是我的数据集示例:
Year North Center South
<dbl> <dbl> <dbl> <dbl>
1 1995 1115. 1057. 876.
2 1996 1559. 1461. 1196.
3 1997 1956. 1923. 1454.
4 1998 1595. 1544. 1139.
5 1999 1912. 1632. 1199.
6 2000 1838. 1868. 1331.
7 2001 1550. 1613. 1204.
8 2002 1598. 1565. 1749.
9 2003 1590. 1654. 1182.
10 2004 1906. 1666. 1203.
11 2005 1523. 1701. 1149.
12 2006 1697. 1741. 1233.
13 2007 1601. 1773. 1267.
14 2008 1937. 1999. 1397.
15 2009 1989. 1330. 1696.
16 2010 1771. 1843 1766.
17 2011 1936. 2529. 1478.
18 2012 1445. 1527. 1745.
这是我的代码:
df %>%
pivot_longer(cols=-`Year`, names_to="area", values_to="value") %>%
ggplot(aes(x=factor(`Year`), y=value, group=area, color=area)) +
geom_point() +
geom_line()
问题在于ggplot按字母顺序设置图例,而我需要按照North-Center-South的顺序。我已经尝试过以下方法,但没有效果:
scale_fill_discrete(breaks=c("North","Center","South"))
如何解决这个问题?
英文:
This is a sample of my dataset
Year North Center South
<dbl> <dbl> <dbl> <dbl>
1 1995 1115. 1057. 876.
2 1996 1559. 1461. 1196.
3 1997 1956. 1923. 1454.
4 1998 1595. 1544. 1139.
5 1999 1912. 1632. 1199.
6 2000 1838. 1868. 1331.
7 2001 1550. 1613. 1204.
8 2002 1598. 1565. 1749.
9 2003 1590. 1654. 1182.
10 2004 1906. 1666. 1203.
11 2005 1523. 1701. 1149.
12 2006 1697. 1741. 1233.
13 2007 1601. 1773. 1267.
14 2008 1937. 1999. 1397.
15 2009 1989. 1330. 1696.
16 2010 1771. 1843 1766.
17 2011 1936. 2529. 1478.
18 2012 1445. 1527. 1745.
and this is my code
df %>%
pivot_longer(cols=-`Year`, names_to="area", values_to="value")%>%
ggplot(aes(x=factor(`Year`), y=value, group=area, color=area)) +
geom_point() +
geom_line()
The problem is that ggplot sets the legend in the alphabetic order, instead I need it as North-Center-South
I have already tried
scale_fill_discrete(breaks=c("North","Center","South")
But nothing happens... how can I solve??
答案1
得分: 0
使用scale_color_discrete
来更改顺序尝试以下内容。
df %>%
pivot_longer(cols=-Year, names_to="area", values_to="value") %>%
ggplot(aes(x=factor(`Commencement Year`), y=value, group=area, color=area)) +
geom_point() +
geom_line() +
geom_hline(data = . %>% filter(area == "North"), aes(yintercept = mean(value)), color = "red", linetype = "dashed") +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
scale_color_discrete(limits = c("North", "Center", "South"))
请注意,我已将代码中的HTML实体代码和HTML编码转换为原始R代码。
英文:
Try this using scale_color_discrete
to change the order.
df %>%
pivot_longer(cols=-Year, names_to="area", values_to="value") %>%
ggplot(aes(x=factor(`Commencement Year`), y=value, group=area, color=area)) +
geom_point() +
geom_line() +
geom_hline(data = . %>% filter(area == "North"), aes(yintercept = mean(value)), color = "red", linetype = "dashed") +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
scale_color_discrete(limits = c("North", "Center", "South"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论