2个具有分类变量的连续变量

时间:2019-04-24 23:07:18

标签: r ggplot2 data-visualization

不确定要使用什么图形。

我目前有两个密度图,每个连续变量Vul和Glob相对于分类变量Continent,可以在下面的数据框中看到。

a = ggplot(Data,aes(x = Glob, fill = Continent)) + geom_density(alpha = 0.4) +labs(title = "Globalisation by Continent")

b = ggplot(Data,aes(x = Vul, fill = Continent)) + geom_density(alpha = 0.4) +labs(title = "Vulnerability by Continent")

grid.arrange(a,b)
 Country       Vul     Glob        Emm
1         Afghanistan 0.5963081 38.11748   9809.225
2             Albania 0.4227595 67.62799   5716.853
3             Algeria 0.3698284 56.07350 145400.217
4              Angola 0.5220609 43.27245  34763.160
5 Antigua and Barbuda 0.4864335 58.04864    531.715
6           Argentina 0.3681622 65.22942 204024.546
     EMMPC              GDPpc1 Code             GDPpc
1 0.299445 625.3395388+FF2:F55  AFG under-performing 
2 1.978763         4578.667934  ALB        performing
3 3.717410         5466.425778  DZA        performing
4 1.291328         5412.692348  AGO        performing
5 5.377649           12900.903  ATG        performing
6 4.746797         12245.25645  ARG        performing
      Continent  Latitude  AvgTemp Coastline ABSLatitude
1          Asia  33.83523 13.64797         0    33.83523
2        Europe  41.14245 12.70404         1    41.14245
3        Africa  28.15894 23.87725         1    28.15894
4        Africa -12.29336 21.97892         1    12.29336
5 North America  17.27750 26.27178         2    17.27750
6 South America -35.38135 14.84694         1    35.38135
  Coastline1 GDPPCLM  GDPpc000s
1          0       0  0.6253395
2          1       0  4.5786679
3          1       0  5.4664258
4          1       0  5.4126923
5          1       1 12.9009030
6          1       1 12.2452564

我想要一张既显示密度图又显示密度图的图,或者一张代表连续变量Vul和Glob对大陆的图。

1 个答案:

答案 0 :(得分:0)

我认为facet_grid()在这种情况下会很好地工作。但是要使用ggplot(在这种情况下为facet_grid())生成图形,使原始数据帧整齐的格式确实非常方便(也由@ eipi10提出)。

 tidy_Data = Data %>% 
  gather(key, value, Vul, Glob)
 tidy_Data
  ggplot(aes(value)) +
  geom_density(aes(fill = key), show.legend = FALSE) +
  facet_grid(vars(Continent), vars(key), scales = "free")

希望您对此有帮助。如果您想进一步了解该功能,建议您查看this official document