首页 > 解决方案 > 在 R 中并排绘制两列

问题描述

我是编码新手,所以这个问题对其他人来说可能很愚蠢。

我正在尝试在 R 中重新创建此图: 在此处输入图像描述

我的代码是:

population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(ggplot2)

pl <- ggplot(df, aes(x= factor(year), y= factor(population), fill= factor(household)))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")


print(pl2)

这就是结果: 在此处输入图像描述 如您所见,尽管我使用的是闪避位置,但家庭列并未在此处显示为列。我无法弄清楚问题是什么。我会很感激任何帮助。

标签: rggplot2plotdata-visualization

解决方案


我认为您正在尝试做的是这样的事情:

population <- c(894, 15736, 42147)
household <- c(215, 4357, 13622)
year <- c(2000, 2010, 2020)
df <- data.frame(year, population, household)

library(tidyr)
df=df%>%pivot_longer(!year)
library(ggplot2)

pl <- ggplot(df, aes(x= year, y=value,fill= name))
pl2 <- pl+ geom_col(position="Dodge")+ labs(x="Year", y= "Population")


print(pl2)

在此处输入图像描述

从你的代码我会做:

pl2=ggplot(df, aes(x= factor(year), y=value,fill= name))+
 geom_bar(stat='identity',position = "dodge")+ labs(x="Year", y= "Population")+
  theme_bw()+
  geom_text(aes(label = value),position=position_dodge(width=0.9),size = 4,vjust=-0.5)
print(pl2)

这样你就有了列上方的数字(theme_bw给出了一个漂亮的情节,但这是个人品味)


推荐阅读