【问题标题】:plot with two columns side by side in R在 R 中并排绘制两列
【发布时间】:2021-12-07 04:52:51
【问题描述】:

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

我正在尝试在 R 中重新创建此图: enter image description here

我的代码是:

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)

结果如下: enter image description here 如您所见,尽管我使用的是闪避位置,但家庭列并未在此处显示为列。我无法弄清楚问题是什么。如有任何帮助,我将不胜感激。

【问题讨论】:

  • 在您的示例中,每个家庭只有一个值。否则它会按预期进行。并且不需要/使用factor(population) - 只需使用population
  • 非常感谢 Dario 有什么方法可以修复它并获得结果吗?
  • 只需添加更多观察结果,以便每年有多个家庭...

标签: r ggplot2 plot data-visualization


【解决方案1】:

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

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 给出了一个漂亮的情节,但这是个人品味)

【讨论】:

  • 非常感谢,这正是我想要的。是的,我要改变它的外观,但首先我只是想正确地创建情节。再次感谢您的帮助。
  • 不客气
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2018-11-29
相关资源
最近更新 更多