r - 在 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)
这就是结果: 在此处输入图像描述 如您所见,尽管我使用的是闪避位置,但家庭列并未在此处显示为列。我无法弄清楚问题是什么。我会很感激任何帮助。
解决方案
我认为您正在尝试做的是这样的事情:
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
给出了一个漂亮的情节,但这是个人品味)
推荐阅读
- c++ - 与指向对象的指针的 std::vector 相比,链表的性能
- google-apps-script - 在 gmail 邮件正文上方显示信息消息
- c++ - Opencv/2DTG,clone() 函数的问题
- javascript - 如何将使用日期范围选择器获得的值转换为两个单独的日期和时间?
- javascript - 购物车中的物品未附加在我的表单中
- r - 沿折线生成一定距离的点
- angular - Ionic PWA SSR,如何在服务器上构建和设置?
- spring-batch - 如何在春季批量编写器中将数据简化为 sftp
- javascript - 使用 flex-box 定位
- angular - 如何隐藏按钮?