【问题标题】:Visualise 3 variables in a graph在图表中可视化 3 个变量
【发布时间】:2019-09-23 21:12:29
【问题描述】:

我有一个包含以下信息的数据框:

Year      Total Population         UK         EEA          NON-EEA
2007          60510               54102       1999          4409
2008          60995               54225       2154          4615
2009          61437               54415       2235          4787
2010          61933               54699       2331          4903
2011          62448               54787       2580          5080 
2012          62864               55042       2671          5151
2013          63230               55309       2762          5160
2014          63653               55375       3042          5236
2015          64212               55642       3204          5365

我如何创建一个图表,在其中我可以看到每年总人口的演变,但也显示英国、欧洲经济区和非欧洲经济区的人口,因为当我们总结所有 3 个变量时,我们有来自 Total 的数据人口列。

另外,我使用了这个代码:

dat <- read.table(text = "Total_Population  United_Kingdom   EEA   Non_EEA
                  2007 60510 54102 1999 4409
                  2008 60995 54225 2154 4615
                  2009 61437 54415 2235 4787
                  2010 61933 54699 2331 4903
                  2011 62448 54787 2580 5080 
                  2012 62864 55042 2671 5151
                  2013 63230 55309 2762 5160
                  2014 63653 55375 3042 5236
                  2015 64212 55642 3204 5365", header = TRUE)

library(reshape2)

dat$row <- seq_len(nrow(dat))
dat2 <- melt(dat, id.vars = "row")

library(ggplot2)

ggplot(dat2, aes(x = variable, y = value, fill = row)) + 
  geom_bar(stat = "identity") +
  xlab("\nCountry of Birth") +
  ylab("Population\n") +
  guides(fill = FALSE) +
  theme_bw()

它给了我条形图,但我想有一些更复杂的东西。

【问题讨论】:

  • 错误来自gather(Year, value, 2007:2009)。应该是gather(group, value, -Year)
  • @NelsonGon Yeeees,它对我有用,它更清晰准确。太感谢了。你可以回答这个问题,我会验证它!再次感谢您!
  • @NelsonGon,是的,这是我的错误,但我纠正了它,现在它向我展示了我所需要的。再一次感谢你!非常感谢!!!
  • 很高兴你成功了!

标签: r dataframe ggplot2


【解决方案1】:

我们可以使用以下内容:

library(dplyr)
library(ggplot2)
library(tidyr)
dat %>% 
mutate(Year=row.names(.)) %>% 
gather(key,value,-c(Year,Total_Population)) %>%   
ggplot(aes(Year,Total_Population,fill=key))+ 
geom_bar(stat="identity")

或者:

dat %>% 
  mutate(Year=row.names(.)) %>% 
  gather(key,value,-c(Year,Total_Population)) %>%   
  ggplot(aes(Year,value,fill=key))+ 
  geom_bar(stat="identity",position="dodge")

数据

dat<-structure(list(Total_Population = c(60510L, 60995L, 61437L, 61933L, 
62448L, 62864L, 63230L, 63653L, 64212L), United_Kingdom = c(54102L, 
54225L, 54415L, 54699L, 54787L, 55042L, 55309L, 55375L, 55642L
), EEA = c(1999L, 2154L, 2235L, 2331L, 2580L, 2671L, 2762L, 3042L, 
3204L), Non_EEA = c(4409L, 4615L, 4787L, 4903L, 5080L, 5151L, 
5160L, 5236L, 5365L)), class = "data.frame", row.names = c("2007", 
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"
))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多