R ggplot2中数据的图例
我的数据是这样的R ggplot2中数据的图例,r,ggplot2,legend,R,Ggplot2,Legend,我的数据是这样的 Week Africa Americas Asia Europe Oceania Burma Cambodia China..Guangxi. China..Yunnan. Laos Thailand Vietnam 1 5 0 6 2912 4 5 0 1 46 26 0 8 2 2 6 0
Week Africa Americas Asia Europe Oceania Burma Cambodia China..Guangxi. China..Yunnan. Laos Thailand Vietnam
1 5 0 6 2912 4 5 0 1 46 26 0 8 2
2 6 0 15 19827 33 12 0 1 127 117 0 19 8
3 7 0 19 42551 49 15 0 1 210 149 0 32 14
4 8 1 22 72721 57 15 0 1 238 171 0 35 16
5 9 1 28 78517 294 15 0 1 251 174 0 35 16
6 10 8 105 86698 2828 31 0 1 252 174 0 43 16
当我想在ggplot2中绘制这张图时,它会给我一张图,但不会给我一个图例,指示哪种线颜色属于哪一组。如何将其添加到图表中
我提供的数据格式是否错误,因此我不会自动执行此操作,或者我在这里做错了什么
干杯,
J我的建议是,首先需要使用tidyr包中的“聚集”功能将此数据帧更改为长数据帧 df% 聚集(df,key=“country”,value=“count”,3:14) 然后在ggplot中,您可以编写如下代码:
library(tidyverse)
#Code
df %>% pivot_longer(-Week) %>%
ggplot(aes(x=Week,y=value,group=name,color=name))+
geom_line()+
scale_color_manual(values=c("Africa"="#8dd3c7",
"Americas"="#ffffb3",
"Asia"="#bebada",
"Europe"="#fb8072",
"Oceania"="#80b1d3",
"Burma"="#fdb462",
"Cambodia"="#b3de69",
"China..Guangxi."="#fccde5",
"China..Yunnan."="#d9d9d9",
"Laos"="#bc80bd",
"Thailand"= "#ccebc5",
"Vietnam"="#ffed6f"))+
labs(color='Country')
ggplot(数据=df,aes(x=周,y=计数,颜色=国家))+
geom_线()
长数据框更好,因为每列有一个变量(例如,“国家”),ggplot最适合这种数据框。图例将自动显示我的建议是,首先需要使用tidyr软件包中的“聚集”功能将此数据帧更改为长数据帧 df% 聚集(df,key=“country”,value=“count”,3:14) 然后在ggplot中,您可以编写如下代码:
library(tidyverse)
#Code
df %>% pivot_longer(-Week) %>%
ggplot(aes(x=Week,y=value,group=name,color=name))+
geom_line()+
scale_color_manual(values=c("Africa"="#8dd3c7",
"Americas"="#ffffb3",
"Asia"="#bebada",
"Europe"="#fb8072",
"Oceania"="#80b1d3",
"Burma"="#fdb462",
"Cambodia"="#b3de69",
"China..Guangxi."="#fccde5",
"China..Yunnan."="#d9d9d9",
"Laos"="#bc80bd",
"Thailand"= "#ccebc5",
"Vietnam"="#ffed6f"))+
labs(color='Country')
ggplot(数据=df,aes(x=周,y=计数,颜色=国家))+
geom_线()
长数据框更好,因为每列有一个变量(例如,“国家”),ggplot最适合这种数据框。图例将自动显示您也可以使用
pivot\u longer()
,这是一种正确的方法,可以使用图例绘制图形,然后按如下方式缩放颜色:
library(tidyverse)
#Code
df %>% pivot_longer(-Week) %>%
ggplot(aes(x=Week,y=value,group=name,color=name))+
geom_line()+
scale_color_manual(values=c("Africa"="#8dd3c7",
"Americas"="#ffffb3",
"Asia"="#bebada",
"Europe"="#fb8072",
"Oceania"="#80b1d3",
"Burma"="#fdb462",
"Cambodia"="#b3de69",
"China..Guangxi."="#fccde5",
"China..Yunnan."="#d9d9d9",
"Laos"="#bc80bd",
"Thailand"= "#ccebc5",
"Vietnam"="#ffed6f"))+
labs(color='Country')
输出:
您也可以使用
pivot\u longer()
这是一种正确的方法,可以使用图例绘制图形,然后按如下方式缩放颜色:
library(tidyverse)
#Code
df %>% pivot_longer(-Week) %>%
ggplot(aes(x=Week,y=value,group=name,color=name))+
geom_line()+
scale_color_manual(values=c("Africa"="#8dd3c7",
"Americas"="#ffffb3",
"Asia"="#bebada",
"Europe"="#fb8072",
"Oceania"="#80b1d3",
"Burma"="#fdb462",
"Cambodia"="#b3de69",
"China..Guangxi."="#fccde5",
"China..Yunnan."="#d9d9d9",
"Laos"="#bc80bd",
"Thailand"= "#ccebc5",
"Vietnam"="#ffed6f"))+
labs(color='Country')
输出:
@陪审员太棒了!如果有帮助的话,请考虑接受这个回答。如果有帮助的话,请考虑接受这个答案。